0

I am using Handlebars for java from : https://github.com/jknack/handlebars.java I have a list of CustomObject and a template file template.hbs. I'm able to iterate over this list by using handle bars {{#each customList}} block.

Now I want to iterate only through even indexed objects in my customList.

Server side :

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; 

part of Template.hbs:

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

But this doesn't iterate my customList instead it just prints my list as string.

1 Answers1

0

I think it's easier to use builtin pseudo vars, so you can accomplish what you ask without messing with custom helpers:

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

Notice that its internal index starts at 0 (interpreted as even), if you need to invert that you can use #unless or @odd.

I also would like to point out the NumberHelper, which offers isEven, isOdd & stripes.

But if you really insist in writing your own custom helper to iterate over even-indexed elements of an Iterable, you're better off studying the source of EachHelper, there you'll also find other pseudo vars.

AndreLDM
  • 2,117
  • 1
  • 18
  • 27