سؤال

I was trying to use the meteor's handlebars helper to include a template. Like, my index.html looks like

<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

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

I don't have {{> myTemplate}} anywhere. My plan is to dynamically inject/render it.

So when I run project, the {{include ...}} is replaced with some gibberish html like below.

<$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'. 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. If it's escaped, Spark won't render it. 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

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. It doesn't appear that include is one of them, but you should be careful using names that sound like keywords.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top