Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple javascript templating function
/**
* Very simple non-hierarchical templating engine
*
* @param name
* @param data
*
* @returns string
*/
function template( name, data ){
// the HTML for the template
var tmpl = document.getElementById('#tmpl-'+name).html();
// loop through data keys and replace template tags
for( var key in data ){
// the regex pattern for replacing this key
var regex = new RegExp( "{{\\s*" + key + "\\s*}}", 'g' );
// replace the template tag for this key
tmpl = tmpl.replace( regex , data[ key ]);
}
// remove any tags that didn't get replaced with data
tmpl = tmpl.replace( /{{.*}}/g, '' );
return tmpl;
}
var myStory = template('story', {
title: 'Once upon a time',
description: 'There was a young flower that wanted to be tree.',
author: 'Jonathan',
});
var someList = ['one','two','three'];
var myListItems = '';
someList.forEach(function(value){
myListItems+= template('list-item', { item: value });
});
var myList = template('list', { listItems: myListItems });
<script type="text/template" id="tmpl-story">
<h2>{{ title }}</h2>
<p>{{ description }}</p>
<div><small>{{ author }}</small></div>
</script>
<script type="text/template" id="tmpl-list-item">
<li>{{ item }}</li>
</script>
<script type="text/template" id="tmpl-list">
<ul>{{ listItems }}</ul>
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment