Skip to content Skip to sidebar Skip to footer

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/temp

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

Solution 2:

Have you tried this way?

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

Just an idea, tell me how it goes.

Solution 3:

The dependency scanning inside require works with string literal dependencies only. You should take a look to the require.js sources, and try to find cjsRequireRegExp variable. As was mentioned before you can just load content using callback notation.

cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g

Solution 4:

I had this problem also while trying to use Backbone/Marionette. Thanks to @Ignacio and @Stanislau Tsishkou above for their insight.

I was able to solve it using the array + callback approach:

var templateName = 'template_name';
var templateHTML = require('text!templates/'+templateName+'.html', function (templateHTML) {
  templateHTML = template;
);

// ...varView = Backbone.Marionette.ItemView.extend({
  // ...template: function() { 
    returnHandlebars.compile(templateHTML).apply(null, arguments); 
  },

  // ...
});

The important parts being:

  1. Ensure you are setting the resulting templateHTML that gets returned in the callback to a variable that is accessible in the proper scope (templateHTML = template is what achieves this).
  2. If using Marionette, ensure you are using a function to generate the template, as this will not try to render the templateHTML before it is actually required.
  3. If using handlebars, as I am in this example, be sure to use the apply method as I have to pass it any arguments that are used in the template function, since Handlebars.compile() returns a function, not the compiled template text.

If you're not using Handlebars, only Underscore or Lodash, the marionette docs give a good example - 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
  });
}

Post a Comment for "Requirejs Text Plugin And Variable Concatenated String"