简体   繁体   English

Global Handlebars模板在流星中返回乱码的HTML

[英]Global Handlebars template returns a gibberish HTML in meteor

I was trying to use the meteor's handlebars helper to include a template. 我试图使用流星的车把帮助器来包含模板。 Like, my index.html looks like 就像我的index.html看起来像

<body>
  {{> body}}
</body>

<template name="body">
  {{include "myTemplate" attr=value}}
</template>

For this I have created a handlebars helper as follows 为此,我创建了一个车把助手,如下所示

Handlebars.registerHelper('include', function(templateName, options) {
  return Template[templateName]({name: 'stackoverflow'});
});

myTemplate.html would look like myTemplate.html看起来像

<template name="myTemplate">
  Hello {{name}}
</template>

I don't have {{> myTemplate}} anywhere. 我在任何地方都没有{{> myTemplate}} My plan is to dynamically inject/render it. 我的计划是动态注入/渲染它。

So when I run project, the {{include ...}} is replaced with some gibberish html like below. 因此,当我运行项目时, {{include ...}}被替换为一些乱码的html,如下所示。

<$label:RjH4gQSmtStAKKaBv><$data:yBKwgoiiHFTKfMec2>
<$landmark:uRZQ3PShZEQwKngFG><$events:WW5fKkc6G5FYKzNrb>
<$watch:GQg4oHk9CyhMw97v4><$isolate:5gXzmhnr9ZCWtWjTB>Hello stackoverflow</$isolate:5gXzmhnr9ZCWtWjTB>
</$watch:GQg4oHk9CyhMw97v4></$events:WW5fKkc6G5FYKzNrb>
</$landmark:uRZQ3PShZEQwKngFG></$data:yBKwgoiiHFTKfMec2>
</$label:RjH4gQSmtStAKKaBv>

Looks like something to do with spark. 看起来与火花有关。 When I run Template.myTemplate({name: 'stackoverflow'}) in the dev console, I get proper string 'Hello stackoverflow' . 当我在开发控制台中运行Template.myTemplate({name: 'stackoverflow'})时,我得到正确的字符串'Hello stackoverflow' I am confused as to why is it giving this gibberish data when used inside a helper? 我很困惑为什么在帮手内部使用时为什么会给出这些乱码?

If you are going to render a template with a helper, you either need to tell Meteor not to escape the string. 如果要使用助手渲染模板,则需要告诉Meteor不要转义字符串。 If it's escaped, Spark won't render it. 如果转义,Spark将不会渲染。 This is a useful default feature that prevents arbitrary code from being injected into your site, and generally makes it clear what's being rendered. 这是一项有用的默认功能,它可以防止将任意代码注入到您的站点中,并且通常可以使呈现的内容清晰可见。

To do this, you can either write it in triple brackets in the template 为此,您可以将其写在模板的三括号中

<template name="body">
  {{{include "myTemplate" attr=value}}}
</template>

or return a SafeString in the helper 或在助手中返回SafeString

Handlebars.registerHelper('include', function(templateName, options) {
  return new Handlebars.SafeString(Template[templateName]({name: 'stackoverflow'}));
});    

On a related note, the Meteor handlebars documentation notes that a few helper names are reserved. 在相关说明中, Meteor车把文档说明了一些助手名称被保留。 It doesn't appear that include is one of them, but you should be careful using names that sound like keywords. 似乎其中不是include是其中之一,但是您应谨慎使用听起来像关键字的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM