Handlebars.js: Nested templates strip “safe” HTML

寵の児 提交于 2019-12-10 13:01:42

问题


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...


回答1:


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);
});


来源:https://stackoverflow.com/questions/9457566/handlebars-js-nested-templates-strip-safe-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!