试图将变量传递给部分而不成功.
尝试1:传递模板上下文
“产品”模板:
From template: {{product.name}} <br> {{> product_buttons}}
“product_buttons”部分:
From partial: {{product.name}}
输出:
From template: Awesome Steel Shoes <br> [object Object] From partial:
我们可以看到2个问题:
> partial不呈现预期值.我也试图用{{> product_buttons this}和{{> product_buttons product = product}获得完全相同的结果
> [object Object]插入输出
尝试2:传递哈希变量
“产品”模板:
From template: {{product.name}} <br> {{> product_buttons thename=product.name}}
“product_buttons”部分:
From partial: {{thename}}
这引发错误Uncaught TypeError:无法从编译的部分读取以下行中未定义的属性“thename”:
return "From partial: " + this.escapeExpression(((helper = (helper = helpers.thename || (depth0 != null ? depth0.thename : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0,{"name":"thename","hash":{},"data":data}) : helper))) ^--- Error is from here + "";
补充笔记
我使用命令行句柄实用程序预编译模板.我使用从npm安装的handlebars 3.0.3,但是输出的句柄-vis“3.0.1”奇怪.我检查路径和安装,也无法修复
编译命令:
handlebars directory/*.handlebars -f file_name.tmpl.js
模板使用示例:
Handlebars.registerPartial('product_buttons',Handlebars.templates.product_buttons); product = {name: 'test'}; html = Handlebars.templates.product({product: product});
任何帮助将不胜感激.谢谢
解决方法
我做了以下步骤来验证你的例子.首先我创建了两个模板:
$cat directory/product.handlebars From template: {{product.name}} <br> {{> product_buttons}} $cat directory/product_buttons.handlebars From partial: {{product.name}}
然后我编译了他们
$handlebars directory/*.handlebars -f file_name.tmpl.js
并得到file_name.tmpl.js:
(function() { var template = Handlebars.template,templates = Handlebars.templates = Handlebars.templates || {}; templates['product_buttons'] = template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { var stack1; return "From partial: " + this.escapeExpression(this.lambda(((stack1 = (depth0 != null ? depth0.product : depth0)) != null ? stack1.name : stack1),depth0)); },"useData":true}); templates['product'] = template({"compiler":[6,data) { var stack1; return "From template: " + this.escapeExpression(this.lambda(((stack1 = (depth0 != null ? depth0.product : depth0)) != null ? stack1.name : stack1),depth0)) + " \n<br>\n" + ((stack1 = this.invokePartial(partials.product_buttons,depth0,{"name":"product_buttons","data":data,"helpers":helpers,"partials":partials})) != null ? stack1 : ""); },"usePartial":true,"useData":true}); })();
然后,我的index.html中包含file_name.tmpl.js,并渲染为这样的模板
Handlebars.registerPartial('product_buttons',Handlebars.templates.product_buttons); var context = {product: {name: 'My product'}}; html = Handlebars.templates.product(context); console.log(html);
给我这个控制台输出:
From template: My product <br> From partial: My product
我看到你没有设置一个上下文到你的产品模板.但是我猜这只是在你的例子中错过了,对吧?
你可以验证(和发布如果不同)你的file_name.tmpl.js的内容?
Btw:我的版本的handlebars也是3.0.1:
$handlebars -v 3.0.1