Last active
April 1, 2022 20:40
-
-
Save daggerhart/a3ec73fb813a1fd542f36ae38d3e9fc6 to your computer and use it in GitHub Desktop.
Simple javascript templating function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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