Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars.js: Nested templates strip "safe" HTML

I'm trying to render a highly variable set of data using a series of nested Handlebars templates and the result that is coming out is completely stripped of HTML tags, despite using a 'triple-stash' and returning a SafeString.

I have data that looks similar to:

{
  "type": "person",
  "details": [
    {"name": "firstname", "value": "joe"},
    {"name": "lastname", "value": "smith"},
    {
      "name": "company",
      "value": "acme",
      "details": [
        {"name": "address", "value": "123 Main St; Somewhere, CA"},
        {"name": "employees", "value": "10+"}
      ]
    }
  ]
}

and I have a couple templates like this:

<template id="personDetails">
  <ul>
    {{{renderPersonDetails details}}}
  </ul> 
</template>

<template id="companyDetails">
  <ol>
    {{{renderCompanyDetails details}}}
  </ol> 
</template>

I pass the entire object into the first template. In the template, I pass the 'details' collection to a registered helper: "renderPersonDetails". The first two elements are simple and are returned as two LI elements. These come out fine.

When we hit the third element that has a "details" property, I pass this object to the companyDetails template, which in turn, will pass the "details" collection to the renderCompanyDetails helper.

The results of the renderCompanyDetails helper are completely stripped of HTML, even though:
1. we're using a triple-stash
2. we're returning the content in a Handlebars.SafeString object
3. if I output the html to the console before returning, I see the HTML as expected

Obviously this example can be simplified dramatically. Our use case, however, requires this type of processing due to the nature of the data and the rendering requirements.

Incidentally, the renderCompanyDetails helper constructs the HTML in the helper. If I try to pass the data from the helper to a third template, and return THAT, the HTML is completely stripped even before I render it...

like image 754
cirruscg Avatar asked Feb 26 '12 21:02

cirruscg


1 Answers

You're not showing the source for renderPersonDetails, but I would bet that it's just returning a string, instead of a Handlebars.SafeString.

Example implementation -- instead of this:

Handlebars.registerHelper('renderPersonDetails', function(data){
  var output = ...;

  return output;
});

do this:

Handlebars.registerHelper('renderPersonDetails', function(data){
  var output = ...;

  return new Handlebars.SafeString(output);
});
like image 137
frontendbeauty Avatar answered Sep 18 '22 03:09

frontendbeauty