user3499265
user3499265

Reputation: 97

How to use a global variable in an array index using Handlebars

I am trying to access an object in an array using a global variable. However, it seems that Handlebars does not allow you to do that. Is there a way around this problem?

This is my code:

<!DOCTYPE html>
<html>
<head>
    <title>Handlebars.js example</title>
</head>
<body>
    <div id="placeholder">This will get replaced by handlebars.js</div>
    <script type="text/javascript" src="handlebars-v1.3.0.js"></script>
    <script id="myTemplate" type="text/x-handlebars-template">
        <table>
        <tbody>
        <tr><th>testing</th><td> <input type="text"><td></tr>
        {{!names[index] is not working}}
------>     {{#each names.[index]}}
        <tr><th> {{this}}</th><td><input type="text"><td></tr>
        {{/each}}
        </tbody>
        </table>
    </script>
    <script type="text/javascript">
        var source = document.getElementById("myTemplate").innerHTML;
        var template = Handlebars.compile(source);
        var index=0;
        var data = {
            names: [
            { name: "foo",id:'id',type:"type"},
            { name: "bar",id:'id' },
            { name: "baz",id:'id' }
            ]};
              document.getElementById("placeholder").innerHTML = template(data);
    </script>
</body>
</html>

I know in this example that I don't need to use a global variable, but with the code that I am using I need to. Please no JQuery, as I can't use it.

EDIT:This is what I am trying to do in the each helper. I am going through each of the attributes of one object. In order to do so, I must select an object at a particular index like names.[0] for example.

Upvotes: 1

Views: 2348

Answers (1)

Volune
Volune

Reputation: 4339

  1. Handlebars can't access a global variable from inside the template. (By the way, index isn't global). You'll probably have to pass index in the context given to template()

  2. {{#each names.[index]}} doesn't resolve to iterate (names[index]) but (names['index'], which is not what you want. ({{#each names.[0]}} works since 0 isn't converted to a string)

  3. The solution:

    • My favorite (example), give the wanted element of names directly in the context

      template({selected:data.names[index]});
      
    • Use a custom helper (example)

      Handlebars.registerHelper('at', function(context, index, options) {
        if( options.fn ) return options.fn(context[index]);
        return context[index];
      });
      

      and

      {{#at names index}}{{#each .}}
          <tr><th>{{@key}}</th><td><input type="text" value="{{.}}"><td></tr>
      {{/each}}{{/at}}
      

Finally, you can also ask for a better solution or a new feature for this issue on github.com/wycats/handlebars.js

Upvotes: 3

Related Questions