How does the syntax of Tagged template strings: fn`text ${10} text`work?

Asked

Viewed 353 times

7

One of the novelties of ES6 are strings template.
How this new syntax applied to functions works?

For example, what does this code?

applyStyle `
  #minhaDiv {
    background-color: ${'#ccf'};
    width: ${50}px;
    height: ${40}px;
    font-size: ${10}px;
    padding: ${5}px;
  }
`;

1 answer

7

Template strings with markup (or tags) are functions that receive arguments in a special way. In normal functions we are used to a syntax minhaFn(a, b, c); and then, within the function, we receive the arguments that these variables had at the time of invoking the function. That is to say:

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 in this way:

the first argument is an array, with the text of the string template, and the second argument and following are the interpolations that the string received.

P: What are interpolations?
R: In the case of this string template `Olá ${nome}! Como estás?`, the variable nome interpolation the string, and it will be passed to argument 1 of the function, and the rest of the text will be broken to argument 0 of the function.

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 of the 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>

  • 1

    How cool! Can you tell me if Babel is able to translate to ECMA5 or tagged template is already compatible with old browsers by default?

  • 1

    @Lucascosta other than IE is already compatible :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

  • 1

    @Lucascosta sim o Babel translate, in this case the example would look like this: https://jsfiddle.net/bt4p82ec/

  • It reminded me Moon at the same time.

  • 1

    @Interesting Phanpy! I don’t know Moon, but I’m curious now :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.