Javascript 带有handlebar.js的递归布局
我有一个简单的对象层次结构,包括:Javascript 带有handlebar.js的递归布局,javascript,json,templates,Javascript,Json,Templates,我有一个简单的对象层次结构,包括: Category String name List childCategories; 我想用一种通用的方式用把手来表示这个布局,但是我在理解如何嵌套布局时遇到了困难。鉴于这种布局: <script id="categories-template" type="text/x-handlebars-template"> {{#categories}} <ul > <li>
Category
String name
List childCategories;
我想用一种通用的方式用把手来表示这个布局,但是我在理解如何嵌套布局时遇到了困难。鉴于这种布局:
<script id="categories-template" type="text/x-handlebars-template">
{{#categories}}
<ul >
<li>
<span>{{name}}</span>
<div>{{#childCategories}}{{/childCategories}}</div>
</li>
</ul>
{{/categories}}
</script>
{{{类别}
-
{{name}}
{{{childCategories}{{/childCategories}}
{{/类别}
为所有子类别重用现有类别模板的最佳方法是什么?是否需要注册处理程序?有更简单的方法吗?
<script id="categories-template" type="text/x-handlebars-template">
<ul>
{{#each categories}}
<li>
<span>{{name}}</span>
<div>
<ul>
{{#each childCategories}}
<li><!-- content: blah-blah-blah --></li>
{{/each}}
</ul>
</div>
</li>
{{/each}}
</ul>
</script>
{{{#每个类别}
-
{{name}}
{{{#每个儿童类别}
{{/每个}}
{{/每个}}
两个模板
<!-- language: html -->
<script id="categories-template" type="text/x-handlebars-template">
{{#categories}}
<ul >
<li>
<span>{{name}}</span>
{{#if childCategories}}
<div>{{&testHelper childCategories}}</div>
{{/if}}
</li>
</ul>
{{/categories}}
</script>
<script id="categories-nested" type="text/html">
{{&testHelper categories}}
</script>
好吧,这将使我有一个层次的深度,但子类别也可能有子类别等等,所以我真的需要它来重用整个布局,如果你知道我的意思的话。然后使用这个答案:当我开始使用HB来获得嵌套模板时,我使用了这个,现在我发现了部分。有区别吗?
Handlebars.registerHelper('testHelper', function(info) {
var template = Handlebars.compile($('script#categories-template').html());
return template(categories);
});