RequireJS文本插件和变量连接字符串
RequireJS text plugin and variable concatenated string
我使用RequireJS文本插件加载一些html模板。当我传递一个字符串文字到require函数,它工作得很好。
var templateHTML = require('text!templates/template_name.html');
但是当我使用变量连接字符串
var templateName = 'template_name';
var templateHTML = require('text!templates/'+templateName+'.html');
抛出以下错误:
Uncaught Error: Module name "text!templates/template_name.html" has not been loaded yet for context: _
对这个问题有什么想法吗?
更新:这是我的测试代码。
require.config({
paths: {
text: '../lib/text',
}
});
define(function (require, exports, module) {
"use strict";
require(['text'], function (text) {
//var templateHTML = require('text!templates/template_name.html');
var templateName = 'template_name';
var templateHTML = require('text!templates/'+templateName+'.html');
});
});
RequireJS文本版本:2.0.3
RequireJS version: 2.1.1
在数组中定义路径,以确保在使用它之前加载它
var templateName = 'template_name';
require(['text!templates/'+templateName+'.html'], templateHTML);
//now you can use
this.template = _.template(templateHTML, {});
你试过这种方法吗?
require.config({
paths: {
text: '../lib/text',
}
});
define(function (require, exports, module) {
"use strict";
var templateName = 'template_name';
require(['text!templates/' + templateName + '.html'], function (template) {
console.log('loaded template: ', template);
});
});
只是一个想法,告诉我是怎么回事。
require中的依赖项扫描只适用于字符串文本依赖项。您应该查看require.js源代码,并尝试找到 cjsrequireeregexp 变量。如前所述,您可以使用回调符号加载内容。
cjsRequireRegExp = /[^.]'s*require's*'('s*["']([^'"'s]+)["']'s*')/g
我在尝试使用Backbone/Marionette时也遇到了这个问题。感谢上面的@Ignacio和@Stanislau Tsishkou的洞察力。
我可以使用数组+回调方法来解决它:
var templateName = 'template_name';
var templateHTML = require('text!templates/'+templateName+'.html', function (templateHTML) {
templateHTML = template;
);
// ...
var View = Backbone.Marionette.ItemView.extend({
// ...
template: function() {
return Handlebars.compile(templateHTML).apply(null, arguments);
},
// ...
});
重要部分是:
- 确保在回调中返回的结果templateHTML设置为在适当范围内可访问的变量(templateHTML = template是实现这一点的)。
- 如果使用的是木偶,确保你使用的是一个函数来生成模板,因为它不会在实际需要之前尝试渲染templateHTML。
- 如果使用handlebars,就像我在这个例子中一样,一定要使用apply方法,因为我必须向它传递模板函数中使用的任何参数,因为handlebars .compile()返回一个函数,而不是编译的模板文本。
如果您不使用手柄,只使用下划线或Lodash,木偶文档给出了一个很好的例子- http://marionettejs.com/docs/v2.4.2/marionette.itemview.html#itemview-render
template : function(serialized_model) {
var name = serialized_model.name;
return _.template(templateHTML)({
name : name
});
}
相关文章:
- 对级联下拉列表使用不同的连接字符串
- 连接字符串时如何留出空格
- 用javascript中的三元运算符连接字符串
- 如何在JavaScript中移除在循环中连接字符串时添加的额外字符
- 在 JavaScript 中连接字符串或数组是否更快
- 我的 base64 连接字符串有 = 字符.如何摆脱它们
- 当字符串为空时,以不同的方式连接字符串
- 这将如何在JavaScript中完成.在连接字符串中使用变量
- 使用JavaScript连接字符串有什么问题
- 使用 JavaScript 警报框在 php 中连接字符串
- 对最后一个条目进行特殊处理的连接字符串的最简单方法
- 连接字符串以打开带有 控件的窗口弹出窗口
- 在 JavaScript / jQuery 中连接字符串
- 连接字符串时是否有用于间距的 JSHint 设置
- 在 Javascript 中连接字符串
- 在 HTML 中连接字符串
- 在名称属性 Struts 中连接字符串
- jQuery 函数在连接字符串后返回 [对象对象]
- 用于屏蔽连接字符串密码的正则表达式
- NodeJS MongoDB 连接字符串问题