Is there a way to set the templateSettings
for lodash when using RequireJS?
Right now in my main startup I have,
require(['lodash', 'question/view'], function(_, QuestionView) {
var questionView;
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\%(.+?)\%\}/g
};
questionView = new QuestionView();
return questionView.render();
});
but it doesn't seem to want to set the templateSettings
globally because when I use _.template(...)
in a module it wants to use the default templateSettings
. The problem is that I don't want to change this setting in every module that uses _.template(...)
.
Bear in mind that if you're using underscore >=1.6.0 or lodash-amd the solution is pretty simple:
"main.js" configuration file
Your "_.js" file:
A module file. It requires our "_" module which requires "underscore" and patches it.
You should pass your _ variable with template settings as function argument or as property in global object (window for browsers or proccess for nodejs).
Or
First option is better.
Based on @Tyson Phalp suggestion, that means this SO question.
I adapted it to your question and I tested it using RequireJS 2.1.2 and SHIM configuration.
This is the
main.js
file, that is where the requireJS config is:Then you should create the
underscoreTplSettings.js
file with your templateSettings like so:So your module
underscore
will contain the underscore library and your template settings.From your application modules just require the
underscore
module, in this way:The only doubt I have is that I'm exporting the same symbol
_
two times, even tough this work I'm not sure if this is considered a good practice.=========================
ALTERNATIVE SOLUTION: This also works fine and I guess it's a little bit more clean avoiding to create and requiring an extra module as the solution above. I've changed the 'export' in the Shim configuration using an initialization function. For further understanding see the Shim config reference.