I have been using the $.each function and some templating so that I can effectively populate/replace my HTML string stored in the temp variable with the title and thumbnail property of the objects stored in the content array.
So for example within the callback function of $.each a regular expression finds the {{title}}, it will replace {{title}} with the contents of obj.title, so that we essentially replace it with the string ‘Speak of the devil and he shall appear’ which is the title property of the object which is iterated over.
The problem I have found is that when I come to append this HTML string (temp variable) to the body. My img HTML tag has been outputted in the wrong way and the contents of obj.title are creating undesired attributes in my img tag
HTML outputted:
<h2> Speak of the devil and he shall appear </h2>
<img appear="" shall="" he="" and="" devil="" the="" of="" alt="Speak" src="images/bane.jpg">
Here is my template:
<script id="blogTemplate" type="chris/template">
<h2> {{title}} </h2>
<img src={{thumbnail}} alt={{title}}>
</script>
And here is my jQuery code:
(function() {
var content = [
{
title: 'Speak of the devil and he shall appear',
thumbnail: 'images/bane.jpg',
},
{
title: 'Me the joker',
thumbnail: 'images/Joker.jpg',
}
];
var template = $.trim( $('#blogTemplate').html() );
$.each( content, function( index, obj ) {
var temp = template.replace( /{{title}}/ig, obj.title )
.replace( /{{thumbnail}}/ig, obj.thumbnail );
console.log(temp);
$('body').append(temp);
});
})();
You need to modify your template to include quotes around the attributes.