43

Possible Duplicate:
Javascript templating engines?

I keep on stumbling upon javascript templating engines and I have no idea what is their purpose. Could anyone explain me like I were five what are those? Can front-end developer make use of these?

Community
  • 1
  • 1
metrampaz
  • 663
  • 1
  • 6
  • 12
  • 2
    JS template engines are for doing what should have been done on the server side. If you're using them, either you're running node.js and *are* doing it server-side, or you're developing a huge ajax application you don't ever intend to show up in search engines. – cHao Mar 03 '12 at 14:53
  • mootools,scriptaculous,yui,jquery,dojo – Sam Arul Raj T Mar 03 '12 at 14:53
  • 2
    Those aren't template engines...those are frameworks. – cHao Mar 03 '12 at 14:57
  • @cHao I generally agree with you, but there are some applications that make good use of them, for example in-house applications or applications where user experience > seo. Another example is http://www.documentcloud.org/home – ebaxt Mar 03 '12 at 15:27
  • 2
    Templating approaches are meant to simplify reuse of markup (in the world of the web). Although @cHao seems to imply their use only belongs on the server except for large-scale web apps, like any tool, when used properly, templates may be used effectively in most contexts in one way or another. For instance, a live Twitter roll, or when you find yourself using the same bit of [markup in Javascript](http://jsfiddle.net/RTUd2/) over and over again. – Jared Farrish Mar 03 '12 at 15:40

1 Answers1

42

JavaScript template engines are often used when writing thick JS-clients or as "normal" template engines when using server-side js like Node.js.

Instead of cluttering the code by generating HTML using string concatenating etc., you instead use a template and interpolate the variable in them.

For instance in the example bellow you pass in an array foo to the template engine which then interpolates (replaces the placeholder ${data}) with item i from the array foo:

//pseudo code
<table>
 <tr>
   for each variable data in foo
    <td>${data}</td>
   end
 <tr>
</table>

In frameworks like backbone.js you typically use a template to implement the view part of the MVC pattern.

There are many different types of template engines in JS. Some are direct ports of server-side frameworks like ERB, HAML etc. Others are developed specially to work with JavaScript i.e Pure

There is a debate of how much expressiveness the template engine should give you because putting logic in your templates is usually a bad thing. Because of this some template engines are specifically designed to not let you put logic in them i.e Mustache

ebaxt
  • 8,287
  • 1
  • 34
  • 36