如何使用 Handlebars 计算数组中有多少项并根据数量输出不同的响应?
How do I count how many items is in an array and output a different response depending on the number using Handlebars?
在这种情况下,我正在准备一个 Handlebars 模板,它可以根据给定列表中的项目数量灵活调整。一般的想法是每个项目将 运行 在列表中向下排列如下:
List Item One
List Item Two
List Item Three
List Item Four
List Item Five
但是一旦超过 5 个项目,它们就应该按如下方式分成两列:
List Item One | List Item Two
List Item Three | List Item Four
List Item Five | List Item Six
我尝试使用 @index
变量(如 documentation 中所述),但是,这仅给出当前迭代的索引,而不是项目的总数大批。例如,这个代码片段:
{{#each items}}
{{#gt @index 4}}
<div class="col-sm-6 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{else}}
<div class="col-sm-12 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{/gt}}
{{/each}}
这将 return 以下内容:
List Item One | List Item Two
List Item Three | List Item Four
List Item Five
List Item Six
List Item Seven
我试过使用 {{#gt items.length 4}}
但这并不像预期的那样工作,并且总是 return 为 false。除非必要,否则最好不要创建自定义助手。
有没有一种方法可以计算数组中有多少项,并且 运行 'greater than' {{#gt}}
以该值为条件?
我发现使用 {{#gt items.length 4}}
的问题在于它获取的是数组中每一项的长度,而不是整个数组的长度。
为了得到想要的效果,需要引用parent数组,方法是:
{{#gt ../items.length 4}}
在这种情况下,以下代码片段提供了正确的结果:
{{#each items}}
{{#gt ../items.length 4}}
<div class="col-sm-6 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{else}}
<div class="col-sm-12 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{/gt}}
{{/each}}
在这种情况下,我正在准备一个 Handlebars 模板,它可以根据给定列表中的项目数量灵活调整。一般的想法是每个项目将 运行 在列表中向下排列如下:
List Item One
List Item Two
List Item Three
List Item Four
List Item Five
但是一旦超过 5 个项目,它们就应该按如下方式分成两列:
List Item One | List Item Two
List Item Three | List Item Four
List Item Five | List Item Six
我尝试使用 @index
变量(如 documentation 中所述),但是,这仅给出当前迭代的索引,而不是项目的总数大批。例如,这个代码片段:
{{#each items}}
{{#gt @index 4}}
<div class="col-sm-6 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{else}}
<div class="col-sm-12 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{/gt}}
{{/each}}
这将 return 以下内容:
List Item One | List Item Two
List Item Three | List Item Four
List Item Five
List Item Six
List Item Seven
我试过使用 {{#gt items.length 4}}
但这并不像预期的那样工作,并且总是 return 为 false。除非必要,否则最好不要创建自定义助手。
有没有一种方法可以计算数组中有多少项,并且 运行 'greater than' {{#gt}}
以该值为条件?
我发现使用 {{#gt items.length 4}}
的问题在于它获取的是数组中每一项的长度,而不是整个数组的长度。
为了得到想要的效果,需要引用parent数组,方法是:
{{#gt ../items.length 4}}
在这种情况下,以下代码片段提供了正确的结果:
{{#each items}}
{{#gt ../items.length 4}}
<div class="col-sm-6 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{else}}
<div class="col-sm-12 list-view-item">
<a href="{{FileRef.textValue}}">{{Title.textValue}}</a>
</div>
{{/gt}}
{{/each}}