RequireJS文本插件和变量串联字符串 [英] RequireJS text plugin and variable concatenated string

查看:278
本文介绍了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, {});

这篇关于RequireJS文本插件和变量串联字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆