Quick Templating in Javascript

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:

template

 

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:

mustache

jQote2

pure

handlebars

underscore

 

hope this helped!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s