【问题标题】:Grails: Asset Pipeline and GSP TemplatesGrails:资产管道和 GSP 模板
【发布时间】:2014-07-21 20:09:39
【问题描述】:

我已从使用 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 文件中,我包含了模板中的代码工作和/或看起来正确所需的几个资产。当我使用资源插件来完成此操作时,事情按预期进行。模板中包含的所有文件都已移至生成的 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>
...

一切正常(尽管理想情况下该文件应该像使用资源插件时一样加载到 HEAD 部分)。

在生产中生成的 HTML 文件如下所示:

...
<link rel="stylesheet" href="/assets/_template.css"/>
<script src="/assets/_template.js" type="text/javascript"></script>
<div>
...
</div>
...

但是,在生产中,所有其他包含的资产(包含在实际 GSP 文件中的文件)具有较长的文件名,类似于 style-6a85c6fa983d13b6f58e12b475e9d35c.css。模板中的 _template.css 和 _template.js 文件没有被转换为这些长文件名之一,如果我尝试访问 /assets/styles.css 路径,我只会得到一个空白页。

【问题讨论】:

    标签: html css grails asset-pipeline


    【解决方案1】:

    通过创建以下标签库,我能够解决问题的第一部分(资产不在 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 创建期间不会被编译,因此无法在生产模式下访问。

    【讨论】:

    • 不编译带有下划线前缀的文件的原因是因为它们被认为是“部分”并且如果您希望编译它们需要包含在其他清单中。有关详细信息,请参阅文档使用章节中的部分部分:bertramdev.github.io/asset-pipeline/guide/usage.html
    猜你喜欢
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2014-12-30
    • 2012-02-24
    相关资源
    最近更新 更多