3

So lets say I generate content from an external handlebars template (through AJAX)

$.ajax({
    url: path,
    dataType: 'html',
    success: function(data) {
        source    = data;
        template  = Handlebars.compile(source);
        //execute the callback if passed
        if (callback) callback(template);
    }
});

Now inside my template.handlebars I output the data I sent using the tags {{this}} etc. But I also include some javascript that are only meant for that template on the bottom of the template (which works fine). However I need to access some of the data sent to the template inside the javascript, is it possible?

A really dumb example which I know doesn't work but should explain what I'm after incase it's unclear. So this could be an example of my template.handlebars file:

<h1>{{question}}</h1>

<script>
//want to access the data sent to template in the JS included
(function($) { //wrap to local scope
    $(document).ready(function() {
        //this doesn't work ofcourse.. but should explain what I'm after
        var question = {{question}};
        console.log(question)
    });
})(jQuery);

Any ideas on how to do that? For me it feels clean to include the JS that is only meant for the particular template this way.

am_
  • 2,378
  • 1
  • 21
  • 28
  • 1
    var question = "{{question}}"; try like this, if it is string. – user10 Oct 08 '13 at 12:05
  • Thanks, that works for strings but not objects nor arrays. I guess I could use JSON and parse that though! If you want to add it as an answer I'll accept it. – am_ Oct 08 '13 at 12:58

1 Answers1

4

When you compile Handlebars template they just return you string by replacing {{expression}}.

So you have to work on each datatypes. For strings use like this.

var question = "{{question}}";

integers should not have any problem. They can be directly placed like this.

var question = {{question}};

I have already worked for objects. You can call helpers for objects and arrays.

refer this stackoverflow post to handle objects.

Community
  • 1
  • 1
user10
  • 5,186
  • 8
  • 43
  • 64
  • 1
    Thanks! creating helpers for accessing objects is a solution I was aware of. What I did now was to add the data I needed in my JS with JSON.stringify() and use JSON.parse("{{objname}}"); to retrieve it. – am_ Oct 08 '13 at 13:14