01月10, 2017

es6之template literals

简单扯一下es6的template literals。

之前我对它的理解比较肤浅,认为它只能做如下的事:

let name = "zpu";
let tpl = `my name is ${name}`;
console.log(tpl);

其实可以在{}中间做很多事,比如做三目运算,如下:

var json = {
    zIndex: 4000,
    width: 100,
    height: "auto",
    className: "modal",
    title: "标题",
    titleIconClass: "",
     tags: ["es6", "template-literals", "es6-in-depth"]
};

 `${
    json.titleIconClass == "" ?
         `<h3 class="dui-dialog-title">${json.title}</h3>` :
         `<h3 class="dui-dialog-title has-icon"><i class="${json.titleIconClass}"></i>${json.title}</h3>`
}`

再比如做for循环:

`${
    json.tags
      .map(tag => `<li>${ tag }</li>`)
      .join("\n      ")
}`

甚至我们还可以写if:

`${
    (function(){
        if(1 != 1){
            return 123;
        }else {
            return 456;
        }
    })()
}`

templates还提供了Tagged Templates的功能,典型的就是String.raw(which prevents \n from being interpreted as a newline):

var text = String.raw`The "\n" newline won"t result in a new line.
It"ll be escaped.`
console.log(text)

我们可以通过它来实现下面的函数功能:

function upper (parts, ...values) {
  return parts.reduce(
    (all, part, i) => all + values[i - 1].toUpperCase() + part
  )
}
var name = "Maurice"
var emotion = "thrilled"
var text = upper`Hello, ${ name }. I am ${ emotion } to meet you!`
console.log(text)
// <- "Hello MAURICE, I am THRILLED to meet you!"

参考资料

本文链接:www.my-fe.pub/post/es6-template-literals.html

-- EOF --

Comments

评论加载中...

注:如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理。