Grails:资产管道和GSP模板

3
我已经从使用资源插件转换到使用新的资产管道插件。然而,我遇到了一个问题,不确定该如何解决。
我使用多个模板(例如:_template.gsp),通过g:render标签从其他GSP文件中包含它们。
_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文件中,我包含了一些必要的资源,以使模板中的代码能够正常工作和/或呈现正确的外观。当我使用资源插件来完成这个任务时,一切都按预期进行。任何包含在模板中的文件都被移动到生成的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>
...

然而,在生产环境中,所有其他包含的资产(包含在实际GSP文件中的文件)都具有较长的文件名,看起来像styles-6a85c6fa983d13b6f58e12b475e9d35c.css。来自模板的_template.css和_template.js文件没有被转换为这些长文件名之一,如果我尝试访问/assets/styles.css路径,则只会得到一个空白页面。

1个回答

0

我能够通过创建以下标签库来解决我的问题的第一部分(资产不在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
    }
  }
}

它是模仿资产管道延迟脚本功能,但更加通用。
而我已经通过简单地重命名资产并删除前导下划线来解决第二个问题。由于某种原因,在 WAR 创建期间不编译带有前导下划线的资产,因此在生产模式下无法访问这些资产。

2
文件名以下划线为前缀的原因是因为它们被认为是“局部文件”,如果您想编译它们,需要在其他清单中包含它们。有关更多详细信息,请参阅文档中使用章节的“局部”部分:https://bertramdev.github.io/asset-pipeline/guide/usage.html - Simon Tarplin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接