سؤال

I am mixing jade with handlebars so that I don't have to write HTML and can have the nice syntax for data-related stuff.

For example, this might be the template for header, header.handlebars.jade

html
  {{#with user}}
  {{if user.username}}
  header Welcome back, {{username}}
  {{/if}}
  {{/with}}

I am wondering if I should precompile this template with jade and then handlebars when I'm using it server-side on node.js? If I don't, I am basically compiling this template 2 times (first jade, then handlebars) on each request.

I am not entirely sure if this plays any role, but it seems that both jade.compile and Handlebars.compile are synchronous functions, which means they are blocking other requests as long as the compilation takes place.

هل كانت مفيدة؟

المحلول

Yes, precompiling your templates can be a good idea. The reason is that using a template generally consists of two steps:

  1. Parsing
  2. Generating a string from the data and the parsed template

Parsing is an expensive operation. It basically consists of a identifying tokens (special words) and building a tree structure. For example:

{{#with author}}
  <h2>By {{firstName}} {{lastName}}</h2>
{{/with}}

This block can be thought as tree with a parent with statement and several children "<h2>By ", firstname, lastName and "</h2>".

When you precompile a template what you're doing is generating code that's the result of parsing and generating that tree structure, so each time you use that code you don't need to parse and generate the tree. You're saving many CPU cycles.

The logic is the same as whether you should read some files synchronously at the start up of your server or to read them every time. If you read the template files at the beginning you do less IO operations, but you're using more memory to store the content of those templates. The same goes for parsing.

What many of us do is identify which assets will be used a lot (templates are usually in this category), cache them in memory and leave the rest to be read on-demand. This means that you can't just change a template and update your site. You need to version your site and in order to make an update you have to kill the Node process and restart it. Whether that's a good idea for your site will depend on how you organize your deployments.

As far as combining Jade and Handlebars, it doesn't look like a good idea because it's a more expensive operation to have render two different templates and because you can only precompile one of them. You can't precompile both of them because one template depends on the result of the other. In your case the "source code" for the Jade template depends on the result of applying the Handlebars template.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top