2

我正在尝试使用http://ejohn.org/blog/javascript-micro-templating构建模板构建器

我的 html 有这个脚本标签

<script type="text/html" id="item_tmpl">
   <div>
   <div class="grid_1 alpha right">
   </div>
    <div class="grid_6 omega contents">
  <p><b><a href="/<%=AdTitle%>"><%=AdTitle%></a>:</b> <%=AdTitle%></p>
  </div>
 </div>
</script>

<script src="${URLUtils.staticURL('/js/shoptheAd.js')}"type="text/javascript"></script>
The Script contains the following code  
        (function(app){
       if (app) {
       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;
      };
      var sitecoresuggestions = {
        "suggestions": [
            {
                "AdTitle": "CheckAd",
                "AdDescription": "",
                "AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/emma-watson-3.ashx",
                "Count": 2,
                "Hit": 0
            },
            {
                "AdTitle": "CheckAd",
                "AdDescription": "",
               "AdImageUrl": "http://demo-kiehls.loreal.photoninfotech.com/~/media/Advertisement Images/kate2.ashx",
                "Count": 2,
                "Hit": 0
            }
        ]
    } ;
      var show_user = tmpl("item_tmpl"), html = "";
    for ( var i = 0; i < sitecoresuggestions.suggestions.length; i++ ) {
      html += show_user( sitecoresuggestions.suggestions[i] );
    }
         console.log(html);
        } else {
            // namespace has not been defined yet
            alert("app namespace is not loaded yet!");
        }
    })(app);
        When the show_user = tmpl("item_tmpl")  is executed  
      i get the error TypeError: document.getElementById(...) is null

在调试时我发现由于某种原因

      <script type="text/html" id="item_tmpl">
      <div>
     <div class="grid_1 alpha right">
     </div>
     <div class="grid_6 omega contents">
    <p><b><a href="/<%=AdTitle%>"><%=AdTitle%></a>:</b> <%=AdTitle%></p>
     </div>
   </div>
   </script>

没有在浏览器中加载任何想法为什么它没有被加载,即使它包含在 head 标记或任何其他导致错误原因的指针中

4

1 回答 1

2

根据帖子:

快速提示:在您的页面中嵌入具有未知内容类型的脚本(这里就是这种情况 - > 浏览器不知道如何执行文本/html 脚本)会被浏览器简单地忽略 - 并且 > 会被搜索引擎忽略和屏幕阅读器。它是一个完美的隐藏设备,可以将模板偷偷溜进你的页面。我喜欢将这种技术用于快速而肮脏的情况,我只需要在页面上放置一个或两个小的 >template 并且想要一些轻巧快速的东西。

所以页面实际上并没有呈现 HTML,我假设您只会在页面中引用它,以便您可以提取并应用于其他对象或项目。正如博主所说,您可以像这样使用它:

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);
于 2012-12-13T18:14:31.280 回答