从.js文件创建资源链接 [英] create link to resource from .js file
问题描述
如何从Grails应用程序中的.js文件创建指向资源(image,.css文件等)的链接,而无需对应用程序上下文进行硬编码?
在.gsp文件中,我可以使用 r:img
或 r:resource
标签由资源插件提供。如果应用程序不使用此插件,则可以使用 g:resource
标记。但是,这些插件都不能用于.js代码。
我当前的解决方案(我讨厌)是将.js代码放在.gsp文件中,然后使用上述的图片标签,例如
< r:script>
var imagePath ='< r:img file =foo / bar.png/>';
< r:脚本>
更新
我的问题是如何从.js文件链接到资源,而不是从GSP的< script>
块中的某些JavaScript代码。在后一种情况下,我可以使用GSP标签,如< r:img>
或< r:resource>
或< g:createLink>
,但忽略.js文件中的GSP标记。
您可以将当前上下文传递给JS。例如,通过将以下片段添加到< head>
中(在您自己的JS之前):
< G:的javascript>
window.appContext ='$ {request.contextPath}';
< / g:javascript>
然后在你的JS的任何地方使用它:
var imagePath = appContext +'/images/foo/bar.png'
How can I create a link to a resource (image, .css file, etc.) from a .js file in a Grails application without hard-coding the application context?
In a .gsp file I can easily do this using the r:img
or r:resource
tags provided by the resources plugin. If the app isn't using this plugin, the g:resource
tag can be used instead. However, neither of these plugins can be used from .js code.
My current solution (which I hate) is to put the .js code in a .gsp file, then use the aforementioned image tags, e.g.
<r:script>
var imagePath = '<r:img file="foo/bar.png"/>';
<r:script>
Update
My question was how to link to a resource from a .js file, not from some JavaScript code within a <script>
block in a GSP. In the latter case, I can use a GSP tag like <r:img>
or <r:resource>
or <g:createLink>
, but GSP tags within .js files are ignored.
You can pass current context to JS. For example by adding following snippet into <head>
(before your own JS):
<g:javascript>
window.appContext = '${request.contextPath}';
</g:javascript>
and then use it anywhere in your JS as:
var imagePath = appContext + '/images/foo/bar.png'
这篇关于从.js文件创建资源链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!