jknack / handlebars.java

Logic-less and semantic Mustache templates with Java
http://jknack.github.io/handlebars.java
Other
1.46k stars 384 forks source link

Helper with no parameters not working in a block #820

Open mkuchtiak opened 3 years ago

mkuchtiak commented 3 years ago

The following test is not working:

    @Test
    void testHelperInLoop() throws IOException {
        Handlebars handlebars = new Handlebars();
        handlebars.registerHelper("greeting", new Helper<Object>() {
            @Override
            public Object apply(final Object context, final Options options) {
                return "Hello";
            }
        });

        ObjectNode document = JsonNodeFactory.instance.objectNode();
        ArrayNode arrayNode = document.putArray("list");
        arrayNode.addObject();
        arrayNode.addObject();
        Context context = Context.newBuilder(document).push(JsonNodeValueResolver.INSTANCE).build();

        Template template = handlebars.compileInline("{{greeting}}{{#each list as |item|}} '{{greeting true}}'{{/each}}");
        assertThat(template.apply(context)).isEqualTo("Hello 'Hello' 'Hello'");
    }

when the template is applied, the result is: Hello '' '' rather than Hello 'Hello' 'Hello'

The test works, when the template is changed to: {{greeting}}{{#each list as |item|}} '{{greeting true}}'{{/each}}

So, when no parameters are passed to handlebar helper the helper is not resolved. This is reproducible only when helper is used in a block (e.g. in #each block)

version: com.github.jknack:handlebars:4.2.0

martin-sladecek commented 3 years ago

The same works well in javascript:

const hb = require('handlebars');

let compiledTemplate = hb.compile("{{#each list as |item|}} {{greeting}} {{/each}}");

hb.registerHelper('greeting', () => {
  return "Hello"
});

let output = compiledTemplate({"list": ["hello", "world"]});
console.log(output)