var ctx = { name: 'jude' }; var tpl = 'hey {{ name }}! {{ name }} is great'; var res = tpl.replace(/\{\{([a-zA-Z ]*)\}\}/g, function(m, g) { return ctx[g.trim()]; }); console.log(res);As you can see at minimal level we need only two things, template and context. A simple syntax ({{ something }} in this case) is then used to inject the context within the template. That's all.
Since context might not contain just singular values always often templating engines provide a for loop of sort. In addition there may be some logic. Sometimes you may use a real programming language even making the line between a templating engine and a real language a fuzzy one.
Applications of Templating
Stencil by splorp (CC BY-NC-ND) |
Static website generators provide yet another example. Rather than having a dynamic component (ie. some database and associated logic) involved you will just end up with something static to serve.
Regardless of where you apply the idea, the fundamentals still remain quite the same. As I deal mostly with frontend these days I'll illustrate a couple of alternatives over there next.
Templating on Frontend
Frontend of sort by myoldpostcards (CC BY-NC-ND) |
In addition to ending up with less code to maintain you will end up with something that other, less technical people might be able to understand. So it's a win-win.
The simplest way to get started is to define a template as a script (ie. <script id="hey" type="text/template">hey {{ name }}! {{ name }} is great</script>) and then refer to that via your code (ie. $('#hey').text()). As I mentioned you may even generate this template using your favorite backend templating solution.
In case you are using RequireJS, you are in luck. You may refer to templates as dependencies at your modules and include them as a part of your build. There are multiple plugins that make this possible.
Transparency provides an interesting alternative to these. You simply define your template as a part of the regular DOM structure. Transparency binds the data to it. In addition it is possible to define directives to deal with some special logic. How elegant is that?
In case you are using RequireJS, you are in luck. You may refer to templates as dependencies at your modules and include them as a part of your build. There are multiple plugins that make this possible.
Transparency provides an interesting alternative to these. You simply define your template as a part of the regular DOM structure. Transparency binds the data to it. In addition it is possible to define directives to deal with some special logic. How elegant is that?