用于渲染下划线模板的grunt contrib-jst未正确格式化

时间:2013-11-01 20:48:16

标签: javascript underscore.js gruntjs jst grunt-contrib-jst

我正在尝试使用grunt-contrib-jst来编译我的下划线模板,但它似乎没有正确渲染/保留变量。这是模板通常的样子:

<script id="header-template" type="text/template">
    <h4><%= subhead %></h4>
    <h1><span class="head-text"><%= head %></span>
      <span class="subtext"><%= subtext %></span>
    </h1>
    <p></p>
  </script>

这是通过grunt呈现的内容:

this["JST"] = this["JST"] || {};

this["JST"]["templates/header.html"] = function(obj) {
obj || (obj = {});
var __t, __p = '', __e = _.escape;
with (obj) {
__p += '<h4>' +
((__t = ( subhead )) == null ? '' : __t) +
'</h4>\n<h1><span class="head-text">' +
((__t = ( head )) == null ? '' : __t) +
'</span>\n  <span class="subtext">' +
((__t = ( subtext )) == null ? '' : __t) +
'</span>\n</h1>\n<p></p>';

}
return __p
};

以下是我设置咕噜声任务的方法:

jst: {
      compile: {
        files: {
          "scripts/templates/all.js": ["templates/*.html"]
        }
      }
    }

当我尝试使用模板时:

var app = app || {};

app.HeaderView = Backbone.View.extend({
    el: '#header-container',
    //template: _.template( $( '#header-template' ).html() ),
    template: JST['templates/header.html'](), //http://stackoverflow.com/questions/8366733/external-template-in-underscore

    initialize: function( templateContent ) {
        this.render(templateContent);
    },
    render: function(templateContent) {
        this.$el.html(this.template(templateContent));
        return this;
    }
});

我收到此错误:

Uncaught ReferenceError: subhead is not defined

知道什么是错的,以及如何维护原始模板的格式化?

1 个答案:

答案 0 :(得分:1)

你说你是

  

[...]尝试使用grunt-contrib-jst编译我的下划线模板

这正是发生的事情。如果您查看_.template docs,您会看到:

  

source 属性在编译的模板函数上可用,以便于预编译。

如果您使用<script>

执行此操作
var t = _.template($('#header-template').html());
console.log(t.source);

你会在控制台中看到这个丑陋的功能。

演示:http://jsfiddle.net/ambiguous/WjNGC/

因此,您的JST任务只是使用_.template编译模板,然后将编译后的模板函数的source属性转储到文件中;然后,当浏览器加载该JavaScript文件时,您将获得已编译的模板。

结果是你可以这样说:

var html = JST['templates/header.html'](data);

并在html中获取填写的模板,而无需在浏览器中编译模板。