browserify 中的空下划线模板
Empty underscore template in browserify
我使用 Browserify 加载 Backbone 视图。
该视图正在渲染一些带有下划线的 html 模板。
当我从 html 模板脚本加载模板标记时,"tmpl2" 方法生成一个空字符串。 browserify 和下划线之间是否存在任何问题,或者为什么它呈现空字符串? (我使用最新版本的 browserify,下划线,backbone,jquery)
View.js:
var $ = require('jquery');
var Backbone = require('backbone');
var _ = require('underscore');
Backbone.$ = $;
var View = Backbone.View.extend({
tmpl1: _.template("<p>hello: <%= name %></p>"), //HTML hardcoded
tmpl2: _.template( $.trim( $('#tmpl').html() ) ), //HTML from template
render: function(){
console.log( $.trim( $('#tmpl').html() ) ); //<p>hello: <%= name %></p> <-- OK
console.log( this.tmpl1({name : 'moe'}) ); //<p>hello: moe</p> <-- OK
console.log( this.tmpl2({name : 'moe'}) ); //(Emptystring) <-- WTF ???
}
});
module.exports = View;
index.html:
<script type="text/template" id="tmpl">
<p>hello: <%= name %></p>
</script>
您的问题很可能是在您编译模板时 DOM 尚未加载。虽然您的渲染函数可能直到稍后才被调用,这就是为什么此时您能够记录模板的原因。
当您声明一个 backbone 视图时,为其 原型 赋值的语句会立即执行。
例如,在您的情况下,会立即执行以下行
tmpl2: _.template( $.trim( $('#tmpl').html() ) ), //HTML from template
您可以改为在初始化函数中编译模板(假设在 DOM 加载后调用)。
例如
initialize: function () {
this.tmpl1 = _.template("<p>hello: <%= name %></p>"); //HTML hardcoded
this.tmpl2 = _.template( $.trim( $('#tmpl').html() ) );
}
然而,这样做的缺点是模板会针对视图的每个实例进行编译,在您的情况下,单独存储模板并 require 可能更有意义并使用它。
我使用 Browserify 加载 Backbone 视图。 该视图正在渲染一些带有下划线的 html 模板。 当我从 html 模板脚本加载模板标记时,"tmpl2" 方法生成一个空字符串。 browserify 和下划线之间是否存在任何问题,或者为什么它呈现空字符串? (我使用最新版本的 browserify,下划线,backbone,jquery)
View.js:
var $ = require('jquery');
var Backbone = require('backbone');
var _ = require('underscore');
Backbone.$ = $;
var View = Backbone.View.extend({
tmpl1: _.template("<p>hello: <%= name %></p>"), //HTML hardcoded
tmpl2: _.template( $.trim( $('#tmpl').html() ) ), //HTML from template
render: function(){
console.log( $.trim( $('#tmpl').html() ) ); //<p>hello: <%= name %></p> <-- OK
console.log( this.tmpl1({name : 'moe'}) ); //<p>hello: moe</p> <-- OK
console.log( this.tmpl2({name : 'moe'}) ); //(Emptystring) <-- WTF ???
}
});
module.exports = View;
index.html:
<script type="text/template" id="tmpl">
<p>hello: <%= name %></p>
</script>
您的问题很可能是在您编译模板时 DOM 尚未加载。虽然您的渲染函数可能直到稍后才被调用,这就是为什么此时您能够记录模板的原因。
当您声明一个 backbone 视图时,为其 原型 赋值的语句会立即执行。
例如,在您的情况下,会立即执行以下行
tmpl2: _.template( $.trim( $('#tmpl').html() ) ), //HTML from template
您可以改为在初始化函数中编译模板(假设在 DOM 加载后调用)。
例如
initialize: function () {
this.tmpl1 = _.template("<p>hello: <%= name %></p>"); //HTML hardcoded
this.tmpl2 = _.template( $.trim( $('#tmpl').html() ) );
}
然而,这样做的缺点是模板会针对视图的每个实例进行编译,在您的情况下,单独存储模板并 require 可能更有意义并使用它。