Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object as parameter to onclick method in handlebars template

I have a JSON that looks like this:

{
list: [
        { name: 'AAA',
          id: 1,
          age: 34
        },
        { name: 'BBB',
          id: 2,
          age: 24
        }
      ]
}

And a template like this:

<ul>
    {{#each list}}
        <li onclick="someFunc({{this}})">{{name}} ({{age}}) </li>
    {{/each}}
</ul>

Basically I just want to pass the current object , to a function that does something with it.

Now if I try it, then the generated HTML just has

 ... onclick="someFunc( [object Object] )" ...

whereas I'd like it to be like this:

 ... onclick="someFunc( {name: 'AAA', id: 1, age: 34} )" ...

How can I fix this?

like image 640
Anand Sriraman Avatar asked Oct 29 '14 22:10

Anand Sriraman


1 Answers

Posting for future references:

Got my answer from here:

Handlebars.js parse object instead of [Object object]

Turns out Handlebar does a toString on the data before pasting into the template. All I had to do was to register a helper method that converts it back to json.

Handlebars.registerHelper('json', function(context) {
    return JSON.stringify(context);
});

<li onclick="someFunc({{json this}})">{{name}} ({{age}}) </li>
like image 173
Anand Sriraman Avatar answered Oct 18 '22 16:10

Anand Sriraman