6

I am working on simple templating enging for my work in javascript.. it needs to be very simple so i am not using Handlebars, moustache or any other robust templating engine available.

I keep reading the word 'PRECOMPILE' or 'COMPILE' template to boost performance. But i am not sure what exactly then mean by that. In my work i cache the template html in my object to avoid hitting the template html everytime.

It's a very simple function which mainly does the following

_template = _template.replace(/\{(.+?)\}/g, function(token, match, number, txt) {
                    return item[match];
                });

item is the object which holds the value to be replaced.

Can someone please tell me what exactly it means when they(handlebars etc) say compile the template. ?

Kamal
  • 1,122
  • 11
  • 18
  • i found this post http://ejohn.org/blog/javascript-micro-templating/ after reading reply from @nrabinowitz.. – Kamal Nov 23 '12 at 22:25

3 Answers3

11

Underscore, Handlebars, and most other JS templates create a function out of the template string. You can then call the function multiple times with different arguments and get the appropriate string of HTML. (I believe both Underscore and Handlebars do this by parsing the template string into JS code and then calling the Function constructor to make the compiled template function.)

When these libraries talk about "precompiling", they mean the initial step of turning the template string into a reusable function. This can be a somewhat heavy step, but it makes rendering the template much faster (faster than simple regex substitution in most cases) so it's more efficient to create the function from the template code and then use it multiple times, rather than recompiling and rendering every time the template is called.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
7

Usually templates are parsed using regex and then converted to function using eval. This called precompile template.

Invoking such functions with some data passed as arguments called render template. So templates doesn't get parsed every time you call it - it already exists in form of function that concatenates and return string.

Inferpse
  • 4,135
  • 1
  • 31
  • 39
-1

Update: I'm incorrect here, see comment below.

Well let's say my template is a sentence with fill in the blanks:

One day, ____ decided he was going to bring _____ with him to the _____.

Compiling the template would be filling in the blanks.

On day, JOHN decided he was going to bring SALLY with him to the BATMAN PREMIER.

Hope metaphor is helpful in this case : )

Costa Michailidis
  • 7,691
  • 15
  • 72
  • 124