Templates 如何在dijit模板中设置相对路径?
我有一个dijit小部件,它相对于dojo的根位于以下位置:Templates 如何在dijit模板中设置相对路径?,templates,dojo,relative-path,Templates,Dojo,Relative Path,我有一个dijit小部件,它相对于dojo的根位于以下位置: /modules/components/myWidget/template/MyWidget.html 现在,除了这个模板之外,我还有一个图像文件需要包含在模板中: /modules/components/myWidget/template/myImage.png 现在,在我的模板文本中: <img src="./myImage.png" /> 但是,这相对于应用程序根(dojo的根和模板位置)进行解析 如何使模
/modules/components/myWidget/template/MyWidget.html
现在,除了这个模板之外,我还有一个图像文件需要包含在模板中:
/modules/components/myWidget/template/myImage.png
现在,在我的模板文本中:
<img src="./myImage.png" />
但是,这相对于应用程序根(dojo的根和模板位置)进行解析
如何使模板直接解析到它的位置?好的,我将执行以下操作,在图像上创建一个附加点,例如:
然后在JavaScript代码中(例如,在小部件的post-create
函数中),我将执行以下操作:
declare([…]{
后创建:函数(){
this.imageNode.src=require.toUrl(“./template/myImage.png”);
}
}
使用require.toUrl
,您实际上可以获得URL,如果您希望将其作为模块加载,则可以使用该URL。这意味着:
require.toUrl(“./template/myImage.png”);
指当前模块路径(/
),可能是/modules/components/myWidget
,然后是模板/myImage.png
require
方法像模块一样require.ToUrl(“./相对/路径”)
app/widget/thingy.js
:
define([
"require" // Needed for relative require.toUrl() calls
/* stuff */
], function(require /*stuff*/){
var blankImage = require.toUrl("../resources/transparent.gif");
/* stuff */
});
运行时,blankImage
值应为“app/resources/transparent.gif”
此外,如果您正在使用Dijits和\u WidgetBase
,您还应该考虑将require
值分配到contextRequire
属性中。这将允许您在HTML模板中执行以下操作:
<div data-dojo-type="./SiblingWidget"></div>
我遇到了一个类似的问题,我需要一个到我的
dojo/text
模板的相对路径
/foo
/js
/stuff
SomeWidget.js
/templates
/MyTemplateForSomeWidget.html
事实证明,您应该给出一个“模块路径”而不是一个“哑url”,因此这将不起作用:
"dojo/text!../../templates/MyTemplateForSomeWidget.html"
它给出了一个很大的错误非理性路径
(没有解释)。结果是不允许您使用“。/
”你当然可以使用一个绝对路径,从一个/
开始,但是在我的例子中,整个路径没有保证,所以我通过在我的dojoConfig
中注册路径来解决这个问题,就像这样
dojoConfig = {
// ...
packages: [
{ name: 'app', location: '/foo/js/app' },
{ name: 'templatePkg', location: '/foo/templates/' },
// ... etc
}
}
然后只需参考templatePkg
作为模板路径的开始,如下所示:
"dojo/text!templatePkg/MyTemplateForSomeWidget.html"
对我来说,“困难的部分”是绕开“包”必须用于JavaScript源代码的想法,并认为其他人可能也有同样的误解
希望这有帮助。
G.有没有任何方法可以直接从模板中执行此操作?我不这么认为,但您可以将
require.toUrl(…)
放在属性中,然后使用
。这也应该可以,但您将始终拥有检索图像URL的那一行代码。