我已经从使用 Resources 插件切换到新的 Asset Pipeline 插件。但是,我遇到了一个我不确定如何解决的问题。
我使用了几个模板(即:_template.gsp),它们通过来自其他 GSP 文件的 g:render 标签包含。
_template.gsp:
<%@ page contentType="text/html;charset=UTF-8" %>
<asset:stylesheet src="_template.css"/>
<asset:javascript src="_template.js"/>
<div>
...
</div>
其他 GSP 文件:
...
<g:render template="/template"/>
...
在我的 _template.gsp 文件中,我包含了模板中的代码正常工作和/或看起来正确所需的几个 Assets 。当我使用资源插件来完成此操作时,一切都按预期进行。模板中包含的所有文件都被移至生成的 GSP 文件的 HEAD 部分。但是,使用 Asset Pipeline 插件时,它们位于调用 GSP 文件中包含模板的相同位置。更糟糕的是,它们没有得到正确处理,因此它们无法正确加载到生成的 HTML 文件中。
例如,在调试中生成的 HTML 文件如下所示
...
<link rel="stylesheet" href="/assets/_template.css?compile=false"/>
<script src="/assets/_template.js?compile=false" type="text/javascript"></script>
<div>
...
</div>
...
一切正常(尽管文件理想情况下应该像使用 Resources 插件时一样加载到 HEAD 部分)。
在生产中生成的 HTML 文件如下所示:
...
<link rel="stylesheet" href="/assets/_template.css"/>
<script src="/assets/_template.js" type="text/javascript"></script>
<div>
...
</div>
...
然而,在生产中,所有其他包含的 Assets (包含在实际 GSP 文件中的文件)的文件名更长,看起来像 styles-6a85c6fa983d13b6f58e12b475e9d35c.css。模板中的 _template.css 和 _template.js 文件没有被转换为这些长文件名之一,如果我尝试访问/assets/styles.css 路径,我只会得到一个空白页面。
最佳答案
通过创建以下标记库,我能够解决问题的第一部分( Assets 不在 HEAD 中):
class TemplateAssetsTagLib
{
// Define the namespace and encoding
static namespace = 'tasset'
static defaultEncodeAs = 'raw'
// Tag called to move the content of this tag to where the assets tag is located (usually the HTML HEAD section)
def head = { attrs, body ->
// Get any existing asset blocks
def assetBlocks = request.getAttribute('templateAssetBlocks')
if(!assetBlocks)
assetBlocks = []
// Add the body of this tag to the asset blocks list
assetBlocks << body()
request.setAttribute('templateAssetBlocks', assetBlocks)
}
// Tag called to load any content that was saved using the head tag
def assets = { attrs ->
// Get all existing asset blocks
def assetBlocks = request.getAttribute('templateAssetBlocks')
if(!assetBlocks)
return
// Output the asset blocks
assetBlocks.each { assetBlock ->
out << assetBlock
}
}
}
它在 Asset Pipeline 延迟脚本功能之后得到镜像,但更通用。
我已经能够通过简单地重命名 Assets 并删除前导下划线来解决第二个问题。由于某些原因,带有前导下划线的 Assets 不会在 WAR 创建期间进行编译,因此在生产模式下无法访问。
关于html - Grails: Assets 管道和 GSP 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24873798/