Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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); 

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top