【问题标题】:Handlebars.js Partial Sub-Template generationHandlebars.js 部分子模板生成
【发布时间】:2013-07-19 20:22:37
【问题描述】:

我在 Handlebars.js 中生成 Partials/Sub 模板时遇到问题。

我已经正确使用了 registerPartials 方法,但它仍然在渲染中出现了某种问题。如果我删除部分模板,它将正确呈现内容。

下面是我正在使用的代码:

<!DOCTYPE html>
<html>
<head>
    <title>Handlebars.js example</title>
</head>
<body>
    <div id="placeholder">This will get replaced by handlebars.js</div>

    <script type="text/javascript" src="handlebars.js"></script>

    <script id="myTemplate" type="x-handlebars-template">
   {{#each allShoes}}
   <li>
   <span> {{name}} - </span> price: {{price}}
   {{> description}}
   </li>
    {{/each}}
</script>




    <script id="shoe-description" type="x-handlebars-template">
<ul>
    <li>{{color}}</li>
    <li>{{size}}</li>
</ul>
</script>

    <script type="text/javascript">
        var source = document.getElementById("myTemplate").innerHTML;
        var template = Handlebars.compile(source);

        // Register the Partial
        //Handlebars.registerPartial("description", $("#shoe-description").html());

       var shoesData = {
                            allShoes:[
                                        {name:"Nike", price:199.00,color:"black", size:10}, 
                                        {name:"Loafers", price:59.00, color:"blue", size:9}, 
                                        {name:"Wing Tip", price:259.00, color:"brown", size:11}
                                        ]
                            };

        Handlebars.registerPartial("description", $("#shoe-description").html());
        document.getElementById("placeholder").innerHTML = template(shoesData);


    </script>



</body>
</html>

registerPartial 有什么问题吗?

感谢任何帮助。

谢谢, 安吉坦纳

【问题讨论】:

    标签: javascript html templating handlebars.js


    【解决方案1】:

    我猜您的呈现问题是要求浏览器呈现无效 HTML 的副作用。您的 HTML 或多或少会以这种结构结束:

    <div>
        <li>
            <ul>...</ul>
        </li>
        ...
    </div>
    

    &lt;li&gt; 必须有一个&lt;ul&gt;&lt;ol&gt;&lt;menu&gt; 作为其父级。我引用specification

    允许的父元素

    ul,ol,菜单

    因此,将 &lt;div&gt; 作为 &lt;li&gt; 的父级是无效的,浏览器可能会重写您的 not-quite-HTML 以使其成为有效的 HTML。这种更正可能会弄乱您的内部清单。修复您的 HTML 并重试:

    <script id="myTemplate" type="x-handlebars-template">
        <ul>
            {{#each allShoes}}
                ...
            {{/each}}
        </ul>
    </script>
    

    演示:http://jsfiddle.net/ambiguous/R23Ak/

    【讨论】:

    • 非常感谢 MU。但是 HTML 通常会呈现内容,对吗?你对 handlebars.js 太棒了 :)
    • 问题是,同样的事情在 Dreamweaver CC 产品 Live View 中不起作用。不知道为什么!将尝试导入您正在使用的 Handlebars 库。会及时通知您。
    • 抱歉,问题是我使用的 jQuery 文件已损坏。它是一个默认导入,就像选中 jsfiddle 中的框一样。但它在我的情况下不起作用。 :) 现在它的工作。
    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 2016-05-04
    • 2013-08-31
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多