簡體   English   中英

ES6 JavaScript模板文字-它們可以做什么和不能做什么

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

模板文字使字符串操作容易得多。 然而:

  1. 與模板庫(例如胡須和車把)相比,它們可以做什么和不能做什么?
  2. 我發現很難找到這些問題的答案:它們可以處理條件嗎? 他們可以處理循環嗎? 他們可以處理功能嗎?

名稱有點模棱兩可,但是模板文字並不能代替模板引擎。 它們的作用只是提供一種更方便的語法來處理字符串。 實際上,目標是像CoffeeScript一樣將字符串插值引入到核心JavaScript中,以及清除多行字符串的可能性。

此代碼...

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

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

...比這更容易維護:

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

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

而且,此代碼...

let str = `Foo
Bar
Baz`;

...比這更具可讀性:

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

即使它們不替換模板引擎,模板文字對預處理字符串也可能很有用(請參見標記的模板文字 )。 使用此功能,我們可以例如使用自定義htmlentities函數對字符串進行轉義:

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

在幕后,帶標簽的模板文字是sprintf在許多編程語言中實現的眾所周知的字符串操作實踐的語法糖:

 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}!`); 

ES6模板文字和模板庫(例如車把)之間存在根本區別,因為ES6模板文字只是語言的一部分,而模板語言/引擎是提供更高級別API的庫,可用於制作大型模板,復雜的字符串(例如HTML頁面),而無需參與在底層使用JavaScript操縱字符串的工作。 換句話說,它們解決了不同的問題。

ES6模板文字可以更准確地視為完成var str = "This is some text with "+someContent+" inserted into it."語法糖var str = "This is some text with "+someContent+" inserted into it." "This is some text with "+someFunction(param, param2)+" inserted into it."

從好的方面來說,您可以在JavaScript中執行的任何邏輯,都可以使用模板文字進行操作,而不利的是,它並沒有為您提供更高級別的API。 就像JavaScript和Ruby之類的其他語言一樣,它只會使JavaScript字符串處理更加流暢。

與標准字符串文字相比,JavaScript模板語言將為您提供不同的表達式和選項集。 它們並不是真正可比的。 模板語言可以在表達式中使用字符串文字/模板字符串 -但是字符串文字只是常規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.`;

因此,數學-以及所有a * b等都以相同的方式工作-但只是為您提供了一種更加通用的語法。

車把幫手(作為“模板語言”的示例)由一組已注冊的功能(來自標准庫或基於標准庫)支持。

// 一些數據

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

//注冊一個“助手”

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>";
});

//使用助手

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

或類似這樣的東西

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM