Search code examples
htmlcssgrails

Adding additional stylesheets/scripts to a grails layout from a view or controller


I want to use a grails layout to define a common layout for all pages in the application. Currently it looks something like this:

<!DOCTYPE html>
<html lang="dk">
<head>
    <meta charset="UTF-8">
    <title><g:layoutTitle default="Title"/></title>
    <asset:stylesheet src="css/default.css"/>
</head>
<body>
    <header><h1><g:layoutTitle default="Title"/></h1></header>
    <main></main>
    <footer></footer>
</body>
<asset:javascript src="jquery-3.4.1.min.js"/>
</html>

Some views may require additional stylesheets or scripts over the defaults provided in the layout, but if I simply add these to the view, they do not appear:

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang=\"dk\">
    <head>
        <meta name="layout" content="index" />
        <asset:stylesheet src="css/additional.css"/>
    </head>
    <body>
        <main>${content}</main>
    </body>
    <asset:javascript src="js/extra.js"/>
</html>

Is there no simple clean way to do this?


Solution

  • Check out: http://docs.grails.org/3.1.1/ref/Tags/layoutBody.html

    Example decorated page:

    <html>
       <head>
            <meta name="layout" content="myLayout" />
            <script src="myscript.js" />
       </head>
       <body>Page to be decorated</body>
    </html>
    

    Example decorator layout:

    <html>
       <head>
            <script src="global.js" />
            <g:layoutHead />
       </head>
       <body><g:layoutBody /></body>
    </html>
    

    Results in:

    <html>
       <head>
            <script src="global.js" />
            <script src="myscript.js" />
       </head>
       <body>Page to be decorated</body>
    </html>