dimanche 1 mars 2015

Grunt compiles handlebars differently—and I can’t load the compiled template


I'm messing around with Handlebars and I'm trying to precompile templates using Grunt. Its output, though, is different from the regular handlebars cli output.


Grunt gives the following output:



this["tpl"] = this["tpl"] || {};
this["tpl"]["templates"] = this["tpl"]["templates"] || {};
this["tpl"]["templates"]["assets/src/templates/test.hbs"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) {
var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression;
return "<h1>"
+ escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"title","hash":{},"data":data}) : helper)))
+ "</h1>\n<p>"
+ escapeExpression(((helper = (helper = helpers.body || (depth0 != null ? depth0.body : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"body","hash":{},"data":data}) : helper)))
+ "</p>";
},"useData":true});


The regular output is this:



(function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['test.hbs'] = template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) {
var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression;
return "<h1>"
+ alias3(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"title","hash":{},"data":data}) : helper)))
+ "</h1>\n<p>"
+ alias3(((helper = (helper = helpers.body || (depth0 != null ? depth0.body : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"body","hash":{},"data":data}) : helper)))
+ "</p>";
},"useData":true});
})();


Loading my template from Grunt, like this, doesn't work:



$.getJSON('assets/src/data/data.json', function(data) {
var testTemplate = tpl['test.hbs'];
var testHtml = testTemplate(data);
$('body').append(testHtml);
});


While loading my template like this works:



<script>
$.getJSON('assets/src/data/data.json', function(data) {
var testTemplate = Handlebars.templates['test.hbs'];
var testHtml = testTemplate(data);
$('body').append(testHtml);
});
</script>


My Gruntfile is as follows:



module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
handlebars: {
compile: {
options: {
namespace: 'tpl.templates',
},
files: {
"assets/build/templates/alltemplates.js": "assets/src/templates/*.hbs"
}
}
},
// etc.


And this is the file structure:


Folder structure of the project





Aucun commentaire:

Enregistrer un commentaire