0

I've a Handlebar template (actually a Moustache template) as

<script id="thumbnail" type="text/x-handlebars-template">

    {{#available}}
    <div class="thumbnail" style="left: {{#coordx}}{{@index}}{{/coordx}};">
        Test Index is {{@index}}
    </div>      
    {{/available}}          

</script>

Here's the data context I'm using.

 var generateThumbnails = {
        "available": [
            "Ruby",
            "Javascript",
            "Python",
            "Erlang",
            "more"
        ],

        coordx : function () {
              return someValue;
        }
    };

On the fly, I'm generating the left css margin as coordx with the function coordx.

In the template, I want to pass the {{@index}} which is used to generate the left margin (which is not working). Like explained at calling function with arguments in mustache javascript

How should I pass the index so that I can get the margin value?

Community
  • 1
  • 1
ptamzz
  • 8,567
  • 30
  • 87
  • 138
  • So are you using Handlebars or Mustache? The syntax will be different for each. If you're using Handlebars, you have invalid syntax. – gfullam Nov 12 '14 at 18:34

2 Answers2

4

if you are trying to use the index in your function you will want to go:

<script id="thumbnail" type="text/x-handlebars-template">

{{#available}}
<div class="thumbnail" style="left: {{coordx @index}}">
    Test Index is {{@index}}
</div>      
{{/available}}          

in your function you would go:

coordx : function (index) {
     var item = index;

     if(item == 0){
         return('15px');
     } else {
         return('30px');
     };
}

this will yield:

<div class="thumbnail" style="left: 15px;">
    Test Index is 0
</div>

<div class="thumbnail" style="left: 30px;">
    Test Index is 1
</div>
GHETTO.CHiLD
  • 2,631
  • 19
  • 30
0

Invalid syntax for Handlebars

If you are using Handlebars (hard to tell from your post), to iterate over arrays, use the {{#each}} helper.

Invalid:

{{#available}}
    ...   
{{/available}}

Valid:

{{#each available}}
    ...   
{{/each}}

Register a Handlebars Helper

To pass @index to a function and perform some operation before returning it, register a custom expression helper in your JS file, instead of passing a function in the JSON model. In Handlebars, functions aren't expected in the JSON context.

Helper:

// Expression Helper
// Return index multiplied by 10 appended with 'px' unit.
Handlebars.registerHelper('coordx', function (index) {
    return (index * 10) + 'px';
});

Final Template:

{{#each available}}
    <div class="thumbnail" style="left: {{coordx @index}};">
        Index {{@index}}: {{this}}
    </div>
{{/each}}

Here is a working JS Fiddle: http://jsfiddle.net/gfullam/L5jrq3dp/

gfullam
  • 9,220
  • 3
  • 46
  • 59