2 mustache的内置tokens

tokens

模板字符串templateStr--编译-->tokens--结合数据-->dom字符串

上面templateStr、templateStr1、templateStr2、templateStr3统统是模板字符串

tokens:是模板字符串的js表示方式。本质是一个js嵌套数组(2维、3维...).tokens是抽象语法数,虚拟节点的开山鼻祖。

 

//编译普通对象成token
const templateStr = `<h3>我今天买了一部{{thing}}手机,花了我{{money}}元,心情好{{mood}}啊</h3>`;

[
    ["text",'<h3>我今天买了一部'],
    ["name",'thing'],
    ["text",'手机,花了我'],
    ["name",'money']
    ["text",'元,心情好'],
    ["name","mood"],
    ["text",'啊']
]
/***************************编译boolean成token********************************/
const templateStr1 = `{{#isShow}}
        <h3>{{message}} vue</h3>
      {{/isShow}}
      `;
[
    ["#","isShow",[
        ["text","<h3>"],
        ["name","message"],
        ["text","vue</h3>"]
    ]]
]
/***********************编译普通数组为tokens********************************/

const templateStr2 = `
      <ul>
          {{#data2}}
            <li>{{.}}</li>
          {{/data2}}
      </ul>
      `;
[
    ["text","<ul>"],
    ["#","data2",[
        ["text","<li>"],
        ["name",'.'],
        ["text",'</li>']
    ]],
    ["text",'</ul>']
]

/***********************对象数组编为tokens********************************/
const templateStr3 = `
        {{#data3}}
         <div>
          <h3>{{name}}的基本信息</h3>
          <p>姓名是:{{name}}</p>
          <p>年龄是:{{age}}</p>
          <p>性别是:{{sex}}</p>
          </div>
        {{/data3}}
      `;
[
    ["#","data3",[
        ["text","<div><h3>"],
        ["name","name"],
        ['text',"的基本信息</h3><p>姓名是:"],
        ["name","name"],
        ["text","</p><p>年龄是:"],
        ["name","age"],
        ["text","</p><p>性别是:"],
        ["name","sex"],
        ["text","</p></div>"]
        
    ]]
]

/***********************嵌套对象数组 编为tokens********************************/
const templateStr4 = `
          {{#data4}}
             <ul>
               <h3>{{name}}的基本信息是:</h3>
               <li>姓名是{{name}}</li>
               <li>年龄是{{age}}</li>
               <li>性别是{{sex}}</li>
               <li>爱好是:
                   <ol>
                    {{#hobbies}}
                       <li>{{.}}</li>
                    {{/hobbies}}
                  </ol>
              </li>

            </ul>
          {{/data4}}
      `;
[
    ["#","data4",[
        ["text","<ul><h3>"],
        ["name","name"],
        ["text","的基本信息是:</h3><li>姓名是"],
        ["name","name"],
        ["text","</li><li>年龄是"],
        ["name","age"],
        ["text","</li><li>性别是"],
        ["name","sex"],
        ["text","</li><li>爱好是:<ol>"],
        ["#","hobbies",[
            ["text","<li>"],
            ["name","."],
            ["text","</li>"]
        ]],
        ["text","</ol></li></ul>"]
    ]]
]

 

mustache库里面的token

parseTemplate函数返回值就是tokens ;注意用自定义变量aaa接受下

const aaa = nestTokens(squashTokens(tokens));
console.log(aaa);
return aaa;

 

posted on 2021-01-09 19:09  章画  阅读(137)  评论(0编辑  收藏  举报

导航