Template strings with tags (or tags ) are functions that receive arguments in a special way. In normal functions we are accustomed to a minhaFn(a, b, c);
syntax and then, within the function, we receive the arguments that these variables had at the moment of invoking the function. That is:
const a = 50;
const b = 5;
const c = 'Km/h';
minhaFn(a, b, c);
function minhaFn(velocidade, tempo, unidade){
const res = (velocidade / tempo) + unidade;
console.log(res);
}
With tagged template string the arguments are distributed like this:
The first argument is an array, with the text of the template string , and the second argument and following are the interpolations that the string received.
Q: What are tweens?
A: In this template string 'Olá ${nome}! Como estás?'
, the nome
variable makes a tween, will be passed to argument 1 of the function, and the rest of the text will be shredded to function argument 0.
Example:
function saudacao(texto, pessoa){
const frase = texto[0] + pessoa + texto[1];
console.log(frase);
}
['Ana', 'João', 'Manuel'].forEach(nome => {
saudacao'Olá ${nome}! Como estás?'
});
The example question, with CSS, allows the function to interact with the arguments if necessary and reconfigure this CSS.
Example:
const style = document.querySelector('style');
const zoom = 5; // 5x
function applyStyle(css, ...valores) {
valores = valores.map(x => typeof x == 'number' ? x * zoom : x);
const rules = css.map((rule, i) => rule.concat(valores[i] || '')).join('');
style.innerHTML = rules;
}
applyStyle '
#minhaDiv {
background-color: ${'#ccf'};
width: ${50}px;
height: ${40}px;
font-size: ${10}px;
padding: ${5}px;
}
';
<style></style>
<div id="minhaDiv">Teste</div>