Search code examples
javascripthandlebars.js

Access array index from output of helper in handlebars


Using handlebars I am trying to log the element at index 1 of an array. The array is the result of the split helper. However, I can't figure out how to do this. Here's my attempt:

{{log (split message '==FUBC==').[1]}}

However, this results in an error:

Debug: internal, implementation, error
    Error: Uncaught error: Parse error on line 4:
...message '==FUBC==')).[1]}}

Is it possible to do what I'm attempting with handlebars? I think one solution would be to use another helper, for example itemAt, like this:

{{log (itemAt (split message '==FUBC==') 1)}}

However, the framework I am working with doesn't implement this helper and I am not able to add new ones. Any ideas?


Solution

  • I can think of two ways, but there might be better ways (haven't used handlebars recently)

    Either use #with to get the array and then access its elements with []

    {{#with (split title "==FUBC==")}}
        {{log [0]}}
    {{/with}}
    

    or directly use the lookup helper.

    {{log (lookup (split title "==FUBC==") 1)}}