I have the follow mustache template:
<script id="pictures" type="text/template">
{{#images}}
<li id="dndtemplate">
<img src={{img}} title={{imgnimi}} alt={{imgnimi}} <span>{{imgnimi}}</span>
</li>
{{/images}}
</script>
and I have to add to the img tag a class "dnd" with auto increment for the number or images I have in the json file. I have done this way but it does not work.
$(function() {
$.getJSON('image.json', function(image) {
var template = $('#pictures').html(function(){
for (var i = 0; i <= img.length[]; i++);
$("#pictures").getElementsByTagName("img").addClass("dnd"+i);
i++;
});
var html = Mustache.to_html(template, image);
$('#dndtemplate').html()
}); //getJSON
}); //function</script>
json is here:
{
"images" : [
{"img" : "images/tytto_60x80.png",
"imgnimi" : "Vilja"},
{"img" : "images/tytto2_60x80.png",
"imgnimi" : "Katri"},
{"img" : "images/tytto3_60x80.png",
"imgnimi" : "Mari"},
{"img" : "images/tytto4_60x80.png",
"imgnimi" : "Larissa"},
{"img" : "images/tytto5_60x80.png",
"imgnimi" : "Alice"},
{"img" : "images/tytto6_60x80.png",
"imgnimi" : "Helena"},
{"img" : "images/poika1_60x80.png",
"imgnimi" : "Jesse"},
{"img" : "images/poika2_60x80.png",
"imgnimi" : "Lauri"},
{"img" : "images/poika3_60x80.png",
"imgnimi" : "Petri"},
{"img" : "images/poika4_60x80.png",
"imgnimi" : "Joonas"},
{"img" : "images/poika5_60x80.png",
"imgnimi" : "Valtteri"},
{"img" : "images/poika6_60x80.png",
"imgnimi" : "Vesa"},
{"img" : "images/auto_110x60.png",
"imgnimi" : "auto"}
]}
I would appreciate any help
As mustache is logic-less templates, you can't apply the incremental logic over here. However there is some work around and following is the code.
First you need to update the template.
<script id="pictures" type="text/template">
<li id="dndtemplate">
<img src="{{img}}" title="{{imgnimi}}" alt="{{imgnimi}}" class="{{dndClass}}" /> <span> {{imgnimi}} </span>
</li>
</script>
Next you need to iterate over the returned JSON object.
var template = $("#pictures").html();
$.each(imgObj.images, function(i, data) {
data.dndClass = "dnd"+i;
var html = Mustache.to_html(template, data);
$('#resultList').append(html);
});
I hope this works for you.