我对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有什么问题吗?
任何帮助都是非常感谢的。
谢谢,安基特·坦纳
发布于 2013-07-21 03:54:28
我猜你的渲染问题是请求浏览器渲染无效HTML的副作用。您的HTML或多或少会以这样的结构结束:
<div>
<li>
<ul>...</ul>
</li>
...
</div>但是<li> 必须有一个<ul>、<ol>或<menu>作为其父对象。我引用specification的话
允许的父元素
ul、ol、menu
因此,将<div>作为<li>的父对象是无效的,浏览器可能会重写您不太熟悉的HTML以使其有效。这种修正可能会把你的内部列表搞得一团糟。修复您的HTML,然后重试:
<script id="myTemplate" type="x-handlebars-template">
<ul>
{{#each allShoes}}
...
{{/each}}
</ul>
</script>演示:http://jsfiddle.net/ambiguous/R23Ak/
https://stackoverflow.com/questions/17764892
复制相似问题