gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:50:36 24 4
gpt4 key购买 nike

我正在尝试使用 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
};

以下是我设置 grunt 任务的方法:

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

知道出了什么问题以及如何维护原始模板的格式吗?

最佳答案

你说的是

[...] trying to use grunt-contrib-jst to compile my underscore templates

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

The source property is available on the compiled template function for easy precompilation.

如果你这样做<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 中填写的模板无需在浏览器中编译模板。

关于javascript - 用于渲染下划线模板的 grunt contrib-jst 格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19735163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com