Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js and Handlebars: HTML compiled is escaped

Im using handlebars in a node aplication, and I have trouble.

This is the template index.html

{{CONTENT}}

This is the code

var fs = require("fs");
var handlebars = require("handlebars");

var data = {
    CONTENT: "<b>Hello world!</b>"
};

var templateFile = fs.readFileSync('./index.html', 'utf8');
var template = handlebars.compile( templateFile );
var html = template(data);

The problem is that the tags <B> are escaped to &lt;B&gt;

How can I avoid this?

like image 609
Enrique Moreno Tent Avatar asked Apr 04 '13 09:04

Enrique Moreno Tent


People also ask

Does handlebars escape HTML?

HTML Escaping Handlebars will not escape a Handlebars.

Can you use handlebars in Javascript?

Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.

How do I use node js handlebars?

HandleBars can be used to render web pages to the client side from data on the server-side. To use handlebars in express, we need to store HTML code into a . hbs extension in the 'views' folder in the source directory as hbs looks for the pages in the views folder. Now, we need to change the default view engine.

What is express handlebars in node js?

A Handlebars view engine for Express which doesn't suck. This package used to be named express3-handlebars . The previous express-handlebars package by @jneen can be found here.


1 Answers

From handlebarsjs.com :

Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash".

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{{body}}}
  </div>
</div>

with this context:

{
  title: "All about <p> Tags",
  body: "<p>This is a post about &lt;p&gt; tags</p>"
}

results in:

<div class="entry">
  <h1>All About &lt;p&gt; Tags</h1>
  <div class="body">
    <p>This is a post about &lt;p&gt; tags</p>
  </div>
</div>

However from my point of view it may defeat the purpose of having a template separated than you're js file.

If you use precompile then use noEscape option:

handlebars.precompile(content, {noEscape: true})
like image 59
Poelinca Dorin Avatar answered Oct 25 '22 11:10

Poelinca Dorin