Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  71] [ 3]  / answers: 1 / hits: 8198  / 11 Years ago, tue, january 7, 2014, 12:00:00

I'm just starting to learn Handlebars.js, I used the Handlebars.js site (http://handlebarsjs.com/expressions.html) to help write this following snippet here:



http://jsfiddle.net/3TxVx/2/



var story = {
url: www.nytimes.com/colonizemars.html,
text: We finally colonized mars!
};

Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString(
<a href=' + object.url + '> + object.text + </a>
);
});

var theTemplateScript = $(#header).html();
var theTemplate = Handlebars.compile (theTemplateScript);

var temp = theTemplate(story);
console.log(temp);

$(function() {
$(document.body).append (temp);
});


Not sure why I get the following error when I run it:



Uncaught TypeError: Cannot read property 'url' of undefined



Thanks!


More From » jquery

 Answers
20

Turns out Handlebars is very picky on the format of the data or context. I made the the following change to the story object and it worked.



    var data = { 
story : {
url: www.nytimes.com/colonizemars.html,
text: We finally colonized mars!
}
};


So now my entire code looks like this:



<script id=header type=text/x-handlebars-template>
{{{link story}}}
</script>
<script type=text/javascript>

Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString(<a href=' + object.url + '> + object.text + </a>
);
});

var data = {
story : {
url: www.nytimes.com/colonizemars.html,
text: We finally colonized mars!
}
};

var theTemplateScript = $(#header).html();
var theTemplate = Handlebars.compile (theTemplateScript);

var temp = theTemplate(data);
console.log(temp);

$(function() {
$(document.body).append (temp);
});

</script>

[#48922] Monday, January 6, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dezmondhumbertob

Total Points: 79
Total Questions: 112
Total Answers: 107

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;