I am trying to covert a Django template to a Handlebars.js template. In the django template I used:
if forloop.counter in Dinsdag
I'm trying to make a custom helper in Handlebars.js that does the same thing. This is what I have so far:
helper.js:
Handlebars.registerHelper('isIn', function(waarde, inWaarde){
$.each($.parseJSON(inWaarde), function(k, v) {
if (k == waarde){
return options.fn(this);
}
});
return options.inverse(this);
});
data.js:
$(function(){
var templateScript = $("#entry-template").html();
var theTemplate = Handlebars.compile(templateScript);
var context = { "dinsdag": {
"uitval2": {
"7": "1",
"9": "1",
"11": "1"
},}}
var html = theTemplate(context);
$('.test').html(html);
$(document.body).append(html);
})
index.html:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js">
</script>
<script type="text/javascript" src="
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<script src="helper.js"></script>
<script src="data.js"></script>
</head>
<body>
<script id="entry-template" type="text/x-handlebars-template">
<ul class="test">
{{#dinsdag}}
{{#isIn 7 uitval2}}
<p>klopt</p>
{{else}}
<p>mwah</p>
{{/isIn}}
{{/dinsdag}}
</ul>
</div>
</div>
</script>
</body>
</html>
This doesn't put anything on screen, and gives the following error:
Uncaught SyntaxError: Unexpected token o
Hoping that someone could help. Keep in mind that I'm a total noob at Handlebars.js
So the problem was that Handlebars "stringifies" JSON
automatically.
removing $.parseJSON
didn't solve it though, I had to specify that it was JSON
to jQuery
.
I did this like this:$.each($.parseJSON(JSON.stringify(inWaarde))