/**
* Very simple find/replace template.
*
* Optional filter function that is used on tags with three curlies. Ex: `{{{this_param_will_be_filtered}}}`
*
* @function {mixin} Application.template
* @param {string} t templateable string
* @param {object} d data object
* @... {string} yourKey containing value to replace
* @param {function(value)} filter a filter function that is passed members of `d` that are templated by triple curlys
* @return {string} string with templates filled
* @author [Jasper Palfree](http://wellcaffeinated.net)
* @license [GPLv3](http://www.gnu.org/licenses/)
* @example
* This will return the text: `this is a template!`
*
* #!javascript
* template("this is a {{what}}", {what: "template!"});
*
* @example
* This will return the text: `this is a template!`
*
* #!javascript
* template("this is a {{nested.what}}", {nested: {what:'template!'} });
*/
function template(t, d, filter){
var data = d;
var ret = t;
var segments = ret.match(/\{?\{\{[a-zA-Z$_][a-zA-Z0-9_.$]*\}\}\}?/g);
for(var x=0, len = segments.length; x < len; x++){
var tags = segments[x].replace(/[\{\}]*/g,'').split('.');
var id = tags.shift();
var repl = (tags.length > 0)?
arguments.callee('{{'+tags.join('.')+'}}',data[id],filter) :
''+data[id];
if(segments[x].match(/^\{\{\{/) && typeof filter === 'function'){
repl = filter(repl);
}
ret = ret.replace(segments[x], repl);
}
return ret;
};
// mimicking retrieval from data source
var entries = [
{id:'1', data: {title:"Title1", content:"<p>This is an entry</p>"}},
{id:'2', data: {title:"Title2", content:"<p>This is another entry</p>"}},
{id:'3', data: {title:"Title3", content:"<p>This is yet another fracking entry</p>"}}
];
// profanity filter as an example
function filterProf(str){
return str.replace('fracking','[censored]');
}
var el = document.getElementById('entryWrap'),
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.