RequireJS文本插件和变量串联字符串
问题描述:
我正在使用RequireJS文本插件加载一些html模板. 当我将字符串文字传递给require函数时,它可以正常工作.
I'm using RequireJS text plugin to load some html templates. When I passing a string literal to the require function it works fine.
var templateHTML = require('text!templates/template_name.html');
但是当我使用变量串联字符串时
But when I using variable concatenated string
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: _
对这个问题有什么想法吗?
Any ideas for this problem?
更新:这是我的测试代码.
UPDATE: Here's my test code.
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版本:2.1.1
RequireJS text version: 2.0.3
RequireJS version: 2.1.1
答
在使用数组之前定义数组中的路径以确保它已加载
Define the path in the array to make sure it loads it before using it
var templateName = 'template_name';
require(['text!templates/'+templateName+'.html'], templateHTML);
//now you can use
this.template = _.template(templateHTML, {});