handlebars.java icon indicating copy to clipboard operation
handlebars.java copied to clipboard

Handlebar Cache Key should contain delimiters

Open dkellenb opened this issue 4 years ago • 1 comments

If once the template was created with the wrong delimiters, the cache returns an invalid result, because delimiters are not part of the cache key.

    @Test
    void delimiterChangeFailsCaching() throws IOException {
        Handlebars handlebars = new Handlebars().with(new HighConcurrencyTemplateCache());

        // compile once with the wrong delimiters due to user input error
        Template invalidTemplate = handlebars.compileInline("Say: ${hello}", "{{", "}}");

        // compile now with the correct delimiters
        Template validTemplate = handlebars.compileInline("Say: ${hello}", "${", "}");

        String result = validTemplate.apply(Map.of("hello", "Hello World"));

        assertThat(result).isEqualTo("Say Hello World"); // <-- fails
    }

dkellenb avatar Aug 16 '21 05:08 dkellenb

This could be solved with:

Handlebars

  public Template compileInline(final String input, final String startDelimiter,
      final String endDelimiter) throws IOException {
    notNull(input, "The input is required.");
    int hashCode = new HashCodeBuilder().append(input).append(startDelimiter).append(endDelimiter).toHashCode();
    String filename = "inline@" + Integer.toHexString(hashCode);
    return compile(new StringTemplateSource(filename, input), startDelimiter, endDelimiter);
  }

dkellenb avatar Aug 16 '21 07:08 dkellenb