ES6 JavaScript template literals - What they can and can't do

ⅰ亾dé卋堺 提交于 2021-02-18 19:00:38

问题


Template literals make string manipulation much easier. However:

  1. What can and what can't they do in comparison to template libraries such as mustache and handlebars?
  2. I found it difficult to find an answer to these questions: Can they handle conditions? Can they handle loops? Can they handle functions?

回答1:


The name is a bit ambiguous, but template literals do not replace template engines. They role is only to provide a more convenient syntax to work with strings. In fact, the objective was to bring string interpolation to core JavaScript like CoffeeScript did, plus the possibility of clean multiline strings.

This code...

let foo = 'Foo',
    bar = 'Bar',
    baz = 'Baz';

console.log(`${foo} ${bar} ${baz}`);

... is easier to maintain than this one:

var foo = 'Foo',
    bar = 'Bar',
    baz = 'Baz';

console.log(foo + ' ' + bar + ' ' + baz);

Moreover, this code...

let str = `Foo
Bar
Baz`;

... is more readable than this one:

var str = 'Foo\n\
Bar\n\
Baz';

Even if they do not replace template engines, template literals may be useful to preprocess strings (see tagged template literals). With this functionality, we can for instance escape strings with a custom htmlentities function:

function htmlentities(raw) {
  let str = raw[0];
    
  return str.replace(/&/g, '&')
            .replace(/>/g, '>')
            .replace(/</g, '&lt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&apos;');
}
    
console.log(htmlentities`&><\"\'`);

Under the hood, tagged template literals are syntactic sugar for a well-known string manipulation practice embodied by sprintf in many programming languages:

let foo = 'Foo',
    bar = 'Bar';

function htmlentities(raw, ...args) {
  console.log('String pieces:');
  console.log(raw);
  console.log('String arguments:');
  console.log(args);
  
  return 'Cool, isn\'t it?';
}

console.log(htmlentities`Hello, ${foo} and ${bar}!`);



回答2:


There is a fundamental difference between the ES6 template literals and a template library such as handlebars in that ES6 template literals are just part of the language, whereas a templating language/engine is a library that provides a higher level API that is useful for making big, complicated strings, like HTML pages without having to get involved manipulating strings in JavaScript on a low-level. In other words, they solve different problems.

ES6 template literals can more accurately be thought of as syntax sugar for doing things like var str = "This is some text with "+someContent+" inserted into it." or "This is some text with "+someFunction(param, param2)+" inserted into it."

On the upside, any logic you could do in JavaScript, you can do with a template literal, and on the downside, it doesn't give you a higher level API. It just makes JavaScript string handling a little bit smoother, like it is in some other languages like Python and Ruby.




回答3:


A JavaScript templating language is going to offer you a different set of expressions and options compared to the standard string literal. They are not really comparable. A templating language may use string literals/template strings within expressions - but string literals are just regular JavaScript.

var message = "Hello, " + name + ". How are you doing today? The room is " + (width * height) + " square feet.";

VS

var message = `Hello, ${name}. How are you doing today? The room is ${width * height} square feet.`;

So, math - and all that stuff a * b etc. works the same way - but just offers you a more versatile syntax.

A handlebars helper (as an example piece of a 'templating language') is backed by a registered set of functions / either from the standard library or build on top of it.

// some data

{
  people: [
    {firstName: "Yehuda", lastName: "Katz"},
    {firstName: "Carl", lastName: "Lerche"},
    {firstName: "Alan", lastName: "Johnson"}
  ]
}

// registering a 'helper'

Handlebars.registerHelper('list', function(items, options) {
  var out = "<ul>";

  for(var i=0, l=items.length; i<l; i++) {
    out = out + "<li>" + options.fn(items[i]) + "</li>";
  }

  return out + "</ul>";
});

// using the helper

{{#list people}}
  {{firstName}} {{lastName}}
{{/list}}

or something like this from a library

{{moment-from-now (now interval=1000)}} // interval is in ms`

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals



来源:https://stackoverflow.com/questions/43660720/es6-javascript-template-literals-what-they-can-and-cant-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!