Tuesday, February 4, 2014

Best templating for Node JS using ExpressJS

I feel the best HTML template tool is EJS. As it is easier to understand as compared to the shorthand style used in Jade.

The three most important things when writing code using EJS are:

1. To print the value of a JavaScript expression as part of your HTML, while escaping any markup characters like <, >, and & to prevent XSS attacks, just use <%= ... %>, like this:
<h3><%= post.title %></h3>
As a good rule of thumb, this is the safest way to output variables in your markup.
2. To print the value of a JavaScript expression as part of your HTML without escaping markup characters (because you are intentionally printing out HTML markup), use <%- %>, like this:
<div class="post-body">

<!--- I hope you validated this HTML against XSS attacks! -->

<%- post.body %>

</div>
3. To simply run some JavaScript inside your template, use <% and %>, like this. Notice that we can shift back into "HTML mode" inside the callback function of our call to "_.each()". We'll switch back to "JavaScript mode" to close the _.each call:
<% _.each(posts, function(post) { %>

  <h3><%= post.title %></h3>

  <div class="post-body">

    <%- post.body %>

  </div>

<% }) %>
The _.each() function, as you've probably guessed, is an Underscore function that acts a lot like jQuery's each() function. It loops over all of our posts and invokes a function (usually written inline with the "function" keyword) once for each post.