Search code examples
javascriptrequirejsamd

RequireJS text plugin and variable concatenated string


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');

It throws following error:

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 text version: 2.0.3
RequireJS version: 2.1.1


Solution

  • 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, {});