Handlebars precompiled templates returns undefined value

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I have a template file test_temp.handlebars. Its content is,

<div>Hello {{name}}</div> 

I compiled the template in my command line using the command,

handlebars test_temp.handlebars -f test_temp.js 

The content of the test_temp.js file is,

(function() { var template = Handlebars.template, templates = Handlebars.templates =Handlebars.templates || {}; templates['test_temp'] = template({"compiler":[5,">=2.0.0"],"main":function(depth0,helpers,partials,data) { var helper, functionType="function", escapeExpression=this.escapeExpression; return "<div>Hello " + escapeExpression(((helper = helpers.name || (depth0 && depth0.name)),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) + "</div>\n"; },"useData":true}); })(); 

Now i read my precompiled template in my html.

var compiledTemplate = Handlebars.templates['test_temp']; var temp_html = compiledTemplate({ name: 'World' }); console.log(temp_html);  //undefined 

Here the value returned to the temp_html is undefined. Kindly let me know how to put this temp_html inside a div.

$("#tempdiv").html(temp_html); 

When I update the temp_html inside the div, the error thrown is,

"Uncaught TypeError: undefined is not a function" 

How to get the precompiled template value and insert it inside a div.

回答1:

See this answer: https://stackoverflow.com/a/22214119/432089

If you downloaded your handlebars from npm, you will get the 2.0 alpha build instead of the stable 1.3.0 build. In other words, it's likely you have 2.0 alpha precompiled templates, but you are using the 1.3.0 runtime JS.



回答2:

Check this fiddle:

http://jsfiddle.net/8TMw4/

<script id="some-template" type="text/x-handlebars-template">     <div>Hello {{name}}</div>     </script>  var source = $("#some-template").html();  var template = Handlebars.compile(source);  console.log(template);  


回答3:

I have accomplished this task applying the following filters:

  • Precompile templates in the backend (Use the build tools you prefer).
  • Load the precompiled template to Ember.TEMPLATES['"+templateName+"'].
  • You must follow ember naming convention in order Ember recognise where your route, view, or component templates are located. This is the job of the Ember.DefaultResolver and ComponentLookup. Specific naming convention could be defined if you implement your custom resolver and assigned it to the application instance.

You could look at this demo example whose build tools are either rake-pipeline or broccoli.



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