0

我正在使用 Handlebars for java:https ://github.com/jknack/handlebars.java 我有一个 CustomObject 列表和一个模板文件 template.hbs。我可以通过使用句柄栏{{#each customList}}块来迭代这个列表。

现在我只想遍历我的 customList 中的索引对象。

服务器端 :

handlebars.registerHelper("even", new Helper<List<?>>() {
        @Override
        public Object apply(List<?> list, Options options)
                throws IOException {
            if(list!=null && list.size()>1) {
                for(int index=0;index<list.size();index++) {
                    if((index+1) % 2 != 0) {
                        options.fn(list.remove(index));
                    }
                }
            }
            return list; 

Template.hbs 的一部分:

{{#even customList}}
  {{customProperty1}}
{{/even}} 

但这不会迭代我的 customList 而是将我的列表打印为字符串。

4

1 回答 1

0

我认为使用内置伪变量更容易,因此您可以完成您的要求而不会弄乱自定义助手:

{{#customList}}
  {{#if @even}}
    {{customProperty1}}
  {{/if}}
{{/customList}}

请注意,它的内部索引从 0 开始(解释为偶数),如果需要反转可以使用 #unless 或 @odd。

我还想指出NumberHelper,它提供 isEven、isOdd 和条纹。

但是,如果您真的坚持编写自己的自定义助手来遍历 Iterable 的偶数索引元素,那么您最好研究一下EachHelper的来源,在那里您还会找到其他伪变量。

于 2017-11-28T01:54:51.553 回答