Simple javascript template system

Code snippets, JavaScript

If you want to use strings as simple templates in javascript, you might want to use my template script. You can do stuff like this:


var template = “Hello my name is {person.name}, I’m {person.age} years old, I like {person.favorites.fruit}, but at most I like {person.favorites.fruit[2]}”;

var replaceVars = {person:{name:”Mark”, age:27, favorites:{fruit:[“apples”,”oranges”, “bananas”] }}};

alert( stroep.core.StringUtil.replaceVars(template , replaceVars) );

// output: Hello my name is Mark, I’m 27 years old, I like apples, oranges, bananas, but at most I like bananas.

You can also use a function inside the template.


var template = “I’m {person.age} years, I feel {customFunction(person.age)}”;

function customFunction(age) {
return age > 50 ? “old” : “young”;
}

alert(  stroep.core.StringUtil.replaceVars(template, {person:{age:27}})  );

// output: I’m 27 years, I feel young

If nothing is found, the variables inside the templates are not going to be replaced.
Alright, here is the javascript util class. Have fun!

http://projects.stroep.nl/javascript/stroep.core.StringUtil.js

Let me know if you spot any bugs.

2 responses to “Simple javascript template system”

  1. Eugene says:

    Thanks, seems like a very useful utility.

    I just added this to the top of the script:

    var stroep = {
    core: {}
    };

  2. in stroep.core.StringUtil.replaceVars(), You need to add a check to see if there are actually any {tag} patterns otherwise the template crashes when no tags are included.

    See https://gist.github.com/74c237dc9b98314cb4d9 for fix

Say something interesting

Please link to code from an external resource, like gist.github.com.