如何动态设置模板字符串?
How to set template string dynamically?
在 Dojo 1.10+ 中有没有办法动态设置基于模板的小部件的 templateString?
例如我试过这样的东西
...
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: undefined,
constructor: function(myTemplate){
var that = this;
//set the template
require(["dojo/text!" + myTemplate], function (template) {
that.templateString = template;
});
}
...
但它不成功,templateString 始终未定义,因此它因 404 错误而崩溃,因为它找不到 html 文件。
这可能吗?
如果只能设置一组有限的模板,您可以使用如下内容:
define([
"dojo/_base/declare",
"dijit/_TemplatedMixin",
"dojo/text!path_to_template1.html",
"dojo/text!path_to_template2.html"
], function(declare, _TemplatedMixin, template1, template2)
{
return declare([_TemplatedMixin],
{
templateToUse: 1,
constructor: function(params)
{
this.templateToUse = params.templateToUse;
},
buildRendering: function()
{
switch(this.templateToUse) {
case 2:
this.templateString = template2;
break;
case 1:
this.templateString = template1;
break;
default:
this.templateString = template1;
};
this.inherited(arguments);
}
}
}
我不得不问这有什么用例,因为我可以看到几个可能更好的替代方案。
- 如果模板明显不同,为什么不创建单独的小部件?您可以使用 dojo 提供的 OOP 或混合技术在它们之间共享功能。
- 可以使用传递给小部件构造函数的参数高度自定义单个模板。您可以将不同的元素附加到道场附加点,甚至可以通过为它们设置 display:none 样式来隐藏某些元素。
在 Dojo 1.10+ 中有没有办法动态设置基于模板的小部件的 templateString?
例如我试过这样的东西
...
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: undefined,
constructor: function(myTemplate){
var that = this;
//set the template
require(["dojo/text!" + myTemplate], function (template) {
that.templateString = template;
});
}
...
但它不成功,templateString 始终未定义,因此它因 404 错误而崩溃,因为它找不到 html 文件。
这可能吗?
如果只能设置一组有限的模板,您可以使用如下内容:
define([
"dojo/_base/declare",
"dijit/_TemplatedMixin",
"dojo/text!path_to_template1.html",
"dojo/text!path_to_template2.html"
], function(declare, _TemplatedMixin, template1, template2)
{
return declare([_TemplatedMixin],
{
templateToUse: 1,
constructor: function(params)
{
this.templateToUse = params.templateToUse;
},
buildRendering: function()
{
switch(this.templateToUse) {
case 2:
this.templateString = template2;
break;
case 1:
this.templateString = template1;
break;
default:
this.templateString = template1;
};
this.inherited(arguments);
}
}
}
我不得不问这有什么用例,因为我可以看到几个可能更好的替代方案。
- 如果模板明显不同,为什么不创建单独的小部件?您可以使用 dojo 提供的 OOP 或混合技术在它们之间共享功能。
- 可以使用传递给小部件构造函数的参数高度自定义单个模板。您可以将不同的元素附加到道场附加点,甚至可以通过为它们设置 display:none 样式来隐藏某些元素。