Search code examples
mustachehandlebars.js

Use @index in a partial parameter


I am not sure how to reference @index (from a #each helper) inside a mustache/handlebars partial parameter map. E.g.

{{#each this.things}}
    <p>Thing {{@index}}</p>
    {{> mypartial id='thing{@index}' }}
{{/each}}

Yields:

    <p>Thing 0</p> <!-- correct -->
    <div id="thing{@index}">/div> <!-- incorrect -->

One option is to change my partial to reference @index within it, but I would like to keep the use of the id partial parameter.


Solution

  • The correct approach to this is to use a concat helper.

    e.g.

    {{> mypartial id=(concat 'thing' @index) }}
    

    Here is the code snippet for my handlebars.java concat helper:

    public class ConcatHelper implements Helper<Object> {
        @Override
        public CharSequence apply(Object context, Options options) {
            StringBuilder sb = new StringBuilder();
            for (Object param : options.params) {
                sb.append(param);
            }
            return sb.toString();
        }
    }
    

    Yields:

    <p>Thing 0</p>
    <div id="thing0">/div>