模板变量不会按预期呈现

时间:2018-02-22 20:00:37

标签: javascript templating

我想测试John Resig微模板引擎https://johnresig.com/blog/javascript-micro-templating/,但它不会渲染123但显示文字模板<%= id1%>

更新代码并收到错误

  

未捕获的TypeError:无法读取属性< innerHTML'为null       at tmpl(index2.html:19)       在index2.html:58

  <!DOCTYPE html>
  <html>
  <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Test</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script>
              // Simple JavaScript Templating
              // John Resig - https://johnresig.com/ - MIT Licensed
              (function(){
                var cache = {};

                this.tmpl = function tmpl(str, data){
                  // Figure out if we're getting a template, or if we need to
                  // load the template - and be sure to cache the result.
                  var fn = !/\W/.test(str) ?
                    cache[str] = cache[str] ||
                      tmpl(document.getElementById(str).innerHTML) :

                    // Generate a reusable function that will serve as a template
                    // generator (and which will be cached).
                    new Function("obj",
                      "var p=[],print=function(){p.push.apply(p,arguments);};" +

                      // Introduce the data as local variables using with(){}
                      "with(obj){p.push('" +

                      // Convert the template into pure JavaScript
                      str
                        .replace(/[\r\t\n]/g, " ")
                        .split("<%").join("\t")
                        .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                        .replace(/\t=(.*?)%>/g, "',$1,'")
                        .split("\t").join("');")
                        .split("%>").join("p.push('")
                        .split("\r").join("\\'")
                    + "');}return p.join('');");

                  // Provide some basic currying to the user
                  return data ? fn( data ) : fn;
                };
              })();    
                  </script>      

  </head>
  <body>
  <script>
  var data = [
    {
      "id":"123",
    },
    {
      "id":"456",
    }          
  ]
  var id1 = data[0].id
  document.body.innerHTML = tmpl("item_tmpl", id1);

  </script>    
  <script type="text/html" id="item_tmpl"> 
    <div>
        <%=id1%>
    </div>
  </script>


  </body>
  </html>

1 个答案:

答案 0 :(得分:2)

您忘记初始化模板功能:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script>
            // Simple JavaScript Templating
            // John Resig - https://johnresig.com/ - MIT Licensed
            (function(){
              var cache = {};

              this.tmpl = function tmpl(str, data){
                // Figure out if we're getting a template, or if we need to
                // load the template - and be sure to cache the result.
                var fn = !/\W/.test(str) ?
                  cache[str] = cache[str] ||
                    tmpl(document.getElementById(str).innerHTML) :

                  // Generate a reusable function that will serve as a template
                  // generator (and which will be cached).
                  new Function("obj",
                    "var p=[],print=function(){p.push.apply(p,arguments);};" +

                    // Introduce the data as local variables using with(){}
                    "with(obj){p.push('" +

                    // Convert the template into pure JavaScript
                    str
                      .replace(/[\r\t\n]/g, " ")
                      .split("<%").join("\t")
                      .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                      .replace(/\t=(.*?)%>/g, "',$1,'")
                      .split("\t").join("');")
                      .split("%>").join("p.push('")
                      .split("\r").join("\\'")
                  + "');}return p.join('');");

                // Provide some basic currying to the user
                return data ? fn( data ) : fn;
              };
            })();    
                </script>      

</head>
<body>
  <div id="container"></div>
<script type="text/html" id="item_tmpl"> 
  <div>
      <%=id1%>
  </div>
</script>
<script>
var data = [
  {
    "id":"123",
  },
  {
    "id":"456",
  }          
]
var id1 = data[0].id
var container = document.getElementById('container');
container.innerHTML = tmpl("item_tmpl", id1);
</script>
</body>
</html>
&#13;
&#13;
&#13;