I'd like to pass template data to a "textfield" helper method I have defined, like this:

{{textfield label="{{label}}"
            id="account_{{attributes.id}}"
            name="account[{{attributes.name}}]"
            class="some-class"
            required="true"}}

(note the {{label}} and {{attributes.id}} references inside the {{textfield}} helper call)

Here is where I set up the template:

data = {
  "attributes": {
    "id": "name",
    "name": "name"
  },
  "label": "Name"
}
var templateHtml = 'markup here';
var template = Handlebars.compile(templateHtml);
var formHtml = template(data);

Here is a jsFiddle.

When I run this, I still see {{placeholders}} in the compiled markup.

How can I accomplish this?

有帮助吗?

解决方案

You're using the incorrect syntax to pass named parameters to your handlebars helper. What you want is something like this:

var data = {
  "attributes": {
    "name": "name"
  }
}
var templateHtml = '{{textfield name=attributes.name}}';
var template = Handlebars.compile(templateHtml);
var formHtml = template(data);

And an updated fiddle: http://jsfiddle.net/3yWn9/1/

其他提示

Well, it seems that compiling the template twice works. Sucks from an efficiency standpoint, but it is what it is. If anyone has an alternative solution, please do post.

var data = { "something": "value", "id": "theId", "theClass": "class-here", "value": "the value" };
var markup = $('#test-template').html();
var template = Handlebars.compile(markup);
var compiled = template(data);
var template2 = Handlebars.compile(compiled);
var compiled2 = template2(data);
$('body').append(compiled2);

Here is a new jsFiddle demonstrating the double compiling.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top