使用require.js全局设置lodash /下划线模板设置 [英] Set lodash / underscore template settings globally using require.js
问题描述
有没有办法为 lodash 设置 templateSettings
使用 RequireJS ?
Is there a way to set the templateSettings
for lodash when using RequireJS?
现在我的主要创业公司I有,
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();
});
但它似乎不想设置 templateSettings
全局因为当我在模块中使用 _。template(...)
时,它想要使用默认的 templateSettings
。问题是我不想在每个使用 _。template(...)
的模块中更改此设置。
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(...)
.
推荐答案
基于@Tyson Phalp建议,这意味着这个问题。
我根据你的问题调整了它,我使用RequireJS 2.1.2和 SHIM配置。
这是 main.js
文件,这是requireJS配置所在的位置:
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:
require.config({
/* The shim config allows us to configure dependencies for
scripts that do not call define() to register a module */
shim: {
underscoreBase: {
exports: '_'
},
underscore: {
deps: ['underscoreBase'],
exports: '_'
}
},
paths: {
underscoreBase: '../lib/underscore-min',
underscore: '../lib/underscoreTplSettings',
}
});
require(['app'],function(app){
app.start();
});
然后你应该创建 underscoreTplSettings.js
文件与您的模板设置如下:
Then you should create the underscoreTplSettings.js
file with your templateSettings like so:
define(['underscoreBase'], function(_) {
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
return _;
});
所以你的模块下划线
将包含下划线库和您的模板设置。
从您的应用程序模块中只需要下划线
模块,这样:
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:
define(['underscore','otherModule1', 'otherModule2'],
function( _, module1, module2,) {
//Your code in here
}
);
我唯一的疑问是我输出相同的符号 _
两次,即使这项工作很艰难,我也不确定这是不是很好。
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.
======== =================
=========================
替代解决方案:
这也可行而且我认为它更加干净,避免创建并需要额外的模块作为上述解决方案。我使用初始化函数更改了Shim配置中的'export'。有关进一步了解,请参阅 Shim配置参考。
//shim config in main.js file
shim: {
underscore: {
exports: '_',
init: function () {
this._.templateSettings = {
evaluate:/\{\{(.+?)\}\}/g,
interpolate:/\{\{=(.+?)\}\}/g,
escape:/\{\{-(.+?)\}\}/g
};
return _; //this is what will be actually exported!
}
}
}
这篇关于使用require.js全局设置lodash /下划线模板设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!