simple Templating in javascript

I often see code, where strings in javascript are concatenated via the + operator. So something like

var myString = 'World';
var myOtherString = 'Hello ' + myString;

This becomes extremely inconvenient when you have to format the text for many languages (because the order of the words is sometimes different). Also, this code is usually not really reusable.
A better approach is to use some sort of templating. For example, one could use some placeholders in the templates and fill them with data, which is passed to an evaluation function. Then the upper code might become:

var myTemplate = 'Hello #{target}';
var myOtherString = evaluatetemplate(myTemplate, {target : 'World'});
var myNextOtherString = evaluatetemplate(myTemplate, {target : 'You'});

So, the template is reusable. A more often used scenario may be fetches. One could define the basic structure for a fetch and reuse this template sometimes. I am sure, everybody knows this problem:

var myFetchTemplate = [
'<fetch mapping="logical">'
, '<entity name="#{entity}">'
, '<all-attributes/>'
, '</entity>'
].join("");
var accountFetch = evaluatetemplate(myFetchTemplate, {entity : 'account'});
var contactFetch = evaluatetemplate(myFetchTemplate, {entity : 'contact'});

I am sure, you get the idea. I brought some demo code to github to share this idea. There is the js-file with the template function and a html page demonstrating the use via quint.

Of course, one could use big libraries with rich functionality (which are available), but 50 lines of code do a lot of this job.

Have fun, christian

,

No comments yet.

Leave a Reply