Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Javascript in Handlebars template

How do we execute javascript in Handlebars template? For example I have the following

<script>
var config = {a: 1}
</script>

I want to be able to get the value of config.a inside a Handlebars template.

like image 354
trivektor Avatar asked Mar 18 '12 06:03

trivektor


1 Answers

You can do this by registering a helper method:

 Handlebars.registerHelper("key_value", function (obj, fn) {
        var soFar = "";
        var key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                soFar += fn({key:key, value:obj[key]});
            }
        }
        return soFar;
    });

And then you can access the key/value pairs in the template.

    <table>
    {{#key_value someData}}
        <tr>
            <td>{{key}}</td>
            <td>{{value}}</td>
        </tr>
    {{/key_value}}
    </table>
like image 148
ebaxt Avatar answered Oct 13 '22 18:10

ebaxt