Details about the template string in JavaScriptES6

Source: Internet
Author: User
Tags i18n
This article mainly introduces the template string in JavaScriptES6. The ES6 version of JS has brought significant improvements in simplification, you can refer to ES6 to introduce a new string literal-template string, in addition to using reverse quotation marks (') for representation, they seem to be no different from common strings. In the simplest case, they are common strings:

context.fillText(`Ceci n'est pas une cha?ne.`, x, y); context.fillText(`Ceci n'est pas une cha?ne.`, x, y);

It is called a template string because the template string introduces a simple string interpolation feature for JS. That is to say, you can easily and elegantly Insert the JS value into the string.

The template string can be used in many places to view the following inconspicuous error message:

function authorize(user, action) { if (!user.hasPrivilege(action)) {  throw new Error(   `User ${user.name} is not authorized to do ${action}.`); }} function authorize(user, action) { if (!user.hasPrivilege(action)) {  throw new Error(   `User ${user.name} is not authorized to do ${action}.`); }}

In the code above, $ {user. name} and $ {action} are called template placeholders. the values of name and action are inserted to the corresponding positions respectively, and then generate "User jorendorff is not authorized to do hockey..

Now we see a more elegant syntax than the + operator. The following are some features you expect:

Template placeholders can be any JavaScript expressions, so function calls and four arithmetic operations are legal. (You can even nest another template string in one template string .)
If a value is not a string, it is converted to a string. For example, if action is an object, the. toString () of the object will be called to convert it to a string.
If you want to use backquotes in template strings, you need to use the backslash \ to escape them.
Similarly, if you want to output $ {in the template string, use a backslash to escape it: $ {or $ \{.
The template string can span multiple rows:

$("#warning").html(` Watch out! 

Unauthorized hockeying can result in penalties of up to ${maxPenalty} minutes.

`); $("#warning").html(` Watch out!

Unauthorized hockeying can result in penalties of up to ${maxPenalty} minutes.

`);

All spaces, line breaks, and indentation in the template string will be output to the result string as is.

Let's take a look at what the template string cannot do:

Special characters are not automatically escaped. To avoid cross-site scripting vulnerabilities, you still need to be careful with untrusted data, which is the same as common strings.
It cannot be used with international libraries and does not process numbers or dates in special language formats.
It is not a substitute for a template engine (such as Mustache or Nunjucks. The template string does not have the syntax for processing loops-A table cannot be constructed using an array ).

To address these restrictions, ES6 provides another template string-tag template for developers and library designers.

The syntax of the tag template is very simple. You only need to introduce a tag before the backquotes. Let's take a look at the first example: SaferHTML. We need to use this tag template to solve the first restriction: automatically escape special characters.

Note that the SaferHTML method is not provided by the ES6 standard library. We need to implement it ourselves:

var message = SaferHTML`

${bonk.sender} has sent you a bonk.

`; var message = SaferHTML`

${bonk.sender} has sent you a bonk.

`;

Here, the SaferHTML tag is a single identifier, and the tag can also be an attribute, such as SaferHTML. escape, or even a method call: SaferHTML. escape ({unicodeControlCharacters: false }). To be accurate, any ES6 member expression or call expression can be used as a tag.

It can be seen that the template string is just the syntactic sugar of string connection, and the tag template is actually a completely different thing: function call.

Therefore, the above Code is equivalent:

var message = SaferHTML(templateData, bonk.sender); var message = SaferHTML(templateData, bonk.sender);

TemplateData is an unchangeable String Array generated by the JS engine based on the source template string. The array here contains two elements, because the template string is separated by placeholders and contains two strings. Therefore, templateData will be like this: Object. freeze (["

"," Has sent you a bonk.

"]

(In fact, templateData has another property: templateData. raw, which is not discussed in this article. The value of this attribute is also an array that contains all the strings in the tag template, but the string contains the escape sequence, which looks more like a string in the source code, such as \ n. ES6 built-in tag String. raw will use these strings .)

This allows the SaferHTML method to parse the two strings at will, and there is a replacement method in N.

As you continue reading the money, you may be struggling to figure out how to implement the SaferHTML method.

Below is an implementation (gist ):

function SaferHTML(templateData) { var s = templateData[0]; for (var i = 1; i < arguments.length; i++) {  var arg = String(arguments[i]);  // Escape special characters in the substitution.  s += arg.replace(/&/g, "&")      .replace(//g, ">");  // Don't escape special characters in the template.  s += templateData[i]; } return s;} function SaferHTML(templateData) { var s = templateData[0]; for (var i = 1; i < arguments.length; i++) {  var arg = String(arguments[i]);   // Escape special characters in the substitution.  s += arg.replace(/&/g, "&")      .replace(//g, ">");   // Don't escape special characters in the template.  s += templateData[i]; } return s;}

With the above method, even if a malicious user name is used, the user is safe.

A simple example is not enough to illustrate the flexibility of the tag template. Let's review the constraints of the template strings listed above to see what else we can do.

The template string does not automatically escape special characters, but we can solve this problem through the tag template. In fact, we can write the SaferHTML method better. From a security perspective, this SaferHTML is very fragile. In HTML, different escape methods are needed in different places, and SaferHTML does not. With a bit of thinking, we can implement a more flexible SaferHTML method, which can escape any HTML in templateData to know which placeholder is pure HTML and which is the attribute of the element, therefore, you need to escape 'and "; which is the URL query string, so you need to use the URL escaping method, rather than the HTML escaping; and so on. This seems a little far-fetched, because HTML Escape efficiency is relatively low. Xin Yun: Yes. The string of the tag template remains unchanged. SaferHTML can cache escaped strings to improve efficiency.
The template string does not have the built-in internationalization feature, but we can add this feature through the tag template. Jack Hsu's article details the implementation process. See the following example:

i18n`Hello ${name}, you have ${amount}:c(CAD) in your bank account.`// => Hallo Bob, Sie haben 1.234,56 $CA auf Ihrem Bankkonto.i18n`Hello ${name}, you have ${amount}:c(CAD) in your bank account.`// => Hallo Bob, Sie haben 1.234,56 $CA auf Ihrem Bankkonto.

The name and amount in the above example are well understood and will be replaced by the corresponding string by the JS engine, but there is also a placeholder not seen: c (CAD), which will be processed by the i18n label, according to the i18n documentation, c (CAD) indicates that amount is a Canadian dollar value.

The template string cannot replace the Mustache and Nunjucks template engines, in part because the template string does not support loops and conditional statements. We can write a tag to implement this type of function:

// Purely hypothetical template language based on// ES6 tagged templates.var libraryHtml = hashTemplate` 
 
 
    #for book in ${myBooks}
  • #{book.title} by #{book.author}
  • #end
`; // Purely hypothetical template language based on// ES6 tagged templates.var libraryHtml = hashTemplate`
    #for book in ${myBooks}
  • #{book.title} by #{book.author}
  • #end
`;

The flexibility is not limited. Note that the parameters of the tag function are not automatically converted to strings. The parameters can be of any type and return values are the same. The tag template even does not need strings. You can use custom tags to create regular expressions, DOM trees, images, Promise representing the entire asynchronous process, JS data structures, GL coloring devices...

Tag templates allow library designers to create powerful domain-specific languages. These languages may not look like JavaScript, but they can be seamlessly embedded into JS and interact with the rest of the language. By the way, I have not seen similar features in other languages. I don't know what this feature brings to us, but the possibilities are very exciting.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.