Ever wanted to do some quick and simple templating in javascript without having to use a templating library. Here’s a little snippet that will help you out:
function template(str,data)
{
for(var key in data)
{
str = str.replace("{{"+key+"}}",data[key]);
}
return str;
}
I find it easier to write that code than to download, include and learn how to use a templating engine.
here’s a complete example:
</pre>
<div id="description">
</div>
<script type="text/javascript">
function template(str,data)
{
for(var key in data)
{
str = str.replace("{{"+key+"}}",data[key]);
}
return str;
}
</script>
<script type="text/javascript">
//the template
var description_template = "\
Name: {{first_name}} {{last_name}}<br/>\
Age: {{age}}<br/>\
Favourite Programming Language: {{prog_lang}}<br/>\
";
//the data
var data = {
first_name:"Nicolas",
last_name:"Brown",
age:20,
prog_lang:"C++"
};
//template away
var html = template(description_template,data);
//show results in a div
var div = document.getElementById("description");
div.innerHTML = html;
</script>
<pre>
the result is:
Easy isnt it? You can replace the “{{” and “}}” with whatever you want to wrap around the placeholder keywords (eg. “[[” and “]]”).
If you need a powerful templating library, here are some alternatives:
hope this helped!
