gpt4 book ai didi

grails - 如何使用Grails Asset Pipeline在 View 中声明要在页脚中呈现的JavaScript Assets

转载 作者:行者123 更新时间:2023-12-02 16:00:57 25 4
gpt4 key购买 nike

由于没有以下延迟选项:

<asset:javascript src="custom_view_script.js"/>

除了资源插件之外,还可以使用什么方法将特定于 View 的脚本放置在结束body标签之前,而无需在布局中全局声明它?

我确实知道:
<asset:deferredScripts/>

但这只能在页面脚本上处理,而不能包括在内。

最佳答案

最简单的方法是使用站点网格。

在您的布局中,您需要

<g:pageProperty name="page.script"/>

在 body 的尽头。

然后,在页面中,您将执行以下操作:
<content tag="script">
<script type="application/javascript">
... your code here ...
</script>
</content>

请注意,内容标签(脚本)是您指定的任何文本,但是要从sitemesh引用该内容,您必须在“页面”之前添加。对此。

但是,请注意,因为sitemesh属性不是累积性的,我的意思是,如果您放置两个内容标记为“script”的节,则只会使用最后一个节。

如果您需要这样做(如我通常所做的那样),则可以使用自定义TagLib(略微修改SitemesTagLib)来实现:
class MyContentTagLib implements RequestConstants {

static namespace = "mycontent"

Closure addContent = { Map attrs, body ->
if( body != null ) {
def htmlPage = getPage()
if( htmlPage instanceof GSPSitemeshPage && attrs.tag ) {
def name = attrs.tag
def sitemeshPage = (GSPSitemeshPage) htmlPage
StreamCharBuffer currentContent = sitemeshPage.getContentBuffer( "page.$name" ) as StreamCharBuffer
StreamCharBuffer newContent = wrapContentInBuffer( body )
if( currentContent ) {
newContent.writeTo( currentContent.writer )
newContent = currentContent
}
sitemeshPage.setContentBuffer( name, newContent )
}
}
}

private AbstractHTMLPage getPage() {
return (AbstractHTMLPage)getRequest().getAttribute(PAGE)
}

private StreamCharBuffer wrapContentInBuffer(Object content) {
if (content instanceof Closure) {
content = content()
}
if (!(content instanceof StreamCharBuffer)) {
// the body closure might be a string constant, so wrap it in a StreamCharBuffer in that case
FastStringWriter stringWriter=new FastStringWriter()
stringWriter.print((Object)content)
StreamCharBuffer newbuffer = stringWriter.buffer
newbuffer.setPreferSubChunkWhenWritingToOtherBuffer(true)
return newbuffer
} else {
return (StreamCharBuffer)content
}
}

}

现在,您可以在布局中保留g:pageProperty,但是您可以在页面中执行以下操作:
<mycontent:addContent tag="script">
<script type="application/javascript">
... your code here ...
</script>
</mycontent:addContent>

那应该收集您放入不同 View 和模板中的所有内容,然后将其显示在g:pageProperty标签所在的最终html中。

关于grails - 如何使用Grails Asset Pipeline在 View 中声明要在页脚中呈现的JavaScript Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com