美文网首页JavaScript
[ECMAScript] Tagged template lit

[ECMAScript] Tagged template lit

作者: 何幻 | 来源:发表于2017-06-14 14:36 被阅读279次

    Template lieterals

    Template literals是一个ES2015特性,它使用反引号包含一个字符串字面量,并且支持嵌入表达式和换行。

    > console.log(`1
    2`);
    
    > 1 
    2
    
    > console.log(`hello ${window.name}`);
    > hello [object window]
    

    \\$\ `需要转义:

    > console.log(`\\
    \`
    \$`);
    
    > \
    `
    $
    

    Tagged template literals

    Template lieterals支持Tag。
    我们可以在Template lieterals前放置一个函数名,用来控制它如何被转换成字符串

    foo`...`
    

    该函数的第一个参数,是组成Template lieterals的由各个嵌入表达式分隔的字符串数组,剩余参数分别是各个嵌入表达式的值。

    const myTag = (strs, ...exprs) => {
        console.log(strs);                  //["x", "\y", ""]
        console.log(strs.raw);              //["x", "\\y", ""]
    
        console.log(exprs);                 //[1, 2]
    
        console.log(strs[1].length);        //2
        console.log(strs.raw[1].length);    //3
    
        return +new Date;
    };
    
    const obj = { a: 1, b: 2 };
    
    const result = myTag`x${obj.a}\\y${obj.b}`;
    console.log(result);                    //1497418977896
    

    注:
    (1)Tag函数可以返回任意对象,不一定是字符串。
    (2)strs有3个元素而不是2个,因为${obj.a}${obj.b}将字符串x${obj.a}y${obj.b}分隔成3个部分,"x""\y",以及尾部的空字符串""
    (3)strs确实是一个数组,但是它还有一个raw属性。其属性值strs.raw也是一个数组,其元素分别表示strs中对应的,经过转义之前的在Template literals中由用户输入的字符串。例如,上例中"\y"未转义之前对应的字符串为"\\\\y",显然这两个字符串长度是不同的。

    > ((strs, ...exprs) => 
        console.log(strs[0].length, strs.raw[0].length)) `\\`;
    
    > 1 2
    

    String.raw

    String.raw是ES2015,内置对象String的一个静态方法,
    把它作为Tag,可以做到只替换嵌入表达式而不转义字符。

    const raw = String.raw`1\\2\\${1+2}`;
    
    console.log(raw);           //1\\2\\3
    console.log(raw.length);    //7
    
    const x = `1\\2\\${1+2}`;
    console.log(x);             //1\2\3
    console.log(x.length);      //5
    

    Escape problem

    Template literals遵从字符串的转义规则:
    (1)以\u开头,后跟4个16进制数字,例如,\u00B1表示±
    (2)以\u开头,使用大括号括起来的16进制数字,例如,\u{2F804}表示
    (3)以\x开头,后跟2个16进制数字,例如,\xB1表示±
    (4)以\\开头,后跟10进制数字,用来表示八进制字面量(注:strict mode下不支持)

    解释器遇到\u\x,如果发现后面的字符不满足以上条件,就会报语法错。例如,

    > latex`\unicode`
    > Uncaught SyntaxError: Invalid Unicode escape sequence
    

    Lifting template literal restriction

    Tagged tamplate literals经常用来实现DSL,
    例如,可以用ECMAScript实现LaTeX

    function latex(strings) {
      // ...
    }
    
    let document = latex`
    \newcommand{\fun}{\textbf{Fun!}}  // works just fine
    \newcommand{\unicode}{\textbf{Unicode!}} // Illegal token!
    \newcommand{\xerxes}{\textbf{King!}} // Illegal token!
    
    Breve over the h goes \u{h}ere // Illegal token!
    `
    

    这些DSL中不可避免的会包含一些以\u或者\x开头的字符串,作为该DSL内部的转义序列,这些情况下Tagged template literals也无能为力。

    Lifting template literal restriction就是一个改善这个问题的TC39提案,目前已经出于Finished Proposals阶段了,即最终会被加入到ES2018规范中。

    注:
    (1)去除\u或者\x的限制,只适用于Tagged template literals,而对于untagged template literals无效,仍然会报语法错。
    (2)为了兼容性,该提案只是将转义后的字符串数组strs,置为单元素数组[undefined],tag函数需要手动处理strs.raw进行处理。

    > ((strs, ...exprs) => {
        console.log(strs);
        console.log(strs.raw);
    }) `something else \unicode`;
    
    > [undefined]
    > ["something else \unicode"]
    

    References

    MDN - Template lieterals
    MDN - String.raw
    tc39/proposals: Finished Proposals
    Template Literal Revision

    相关文章

      网友评论

        本文标题:[ECMAScript] Tagged template lit

        本文链接:https://www.haomeiwen.com/subject/ihmsqxtx.html