2015-06-17 65 views
0

頁腳中呈現由於不存在用於延遲選項:如何在視圖中聲明的javascript資產使用Grails資產管道

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

還有什麼可使用資源插件外,將View在關閉body標籤之前的特定腳本,而不是在佈局中全局聲明它?

我不知道:

<asset:deferredScripts/> 

但只處理在頁面腳本,不包括。

回答

0

最簡單的方法是使用網站網格。

在你的佈局,你需要把

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

在身體的末端。

然後在頁面中,你會做這樣的事情:

<content tag="script"> 
<script type="application/javascript"> 
... your code here ... 
</script> 
</content> 

注意標記的內容(劇本)是您指定的,而是指從SiteMesh的你在前面加上「頁面內容的任何文本。 「到它。

但是,要小心,因爲sitemesh屬性不是累積的,我的意思是,如果你把兩個部分的內容tag =「script」,只有最後一個將被使用。

如果你需要,我平時做,你可以通過使用稍微修改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> 

這應該收集所有你把不同的意見和模板的內容,然後在最終的HTML顯示它在您的G:pageProperty標籤。

+0

這是一個很好的解決方案,使用sitemash。然而,我試圖找到一種方法來處理Grails Asset插件。 – Micor

+0

我試過自己用資產插件做這件事毫無用處,既然你說「資源插件之外」...... – ncerezo