Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Include template from external location

Tags:

grails

How do I include external GSPs or template in the GSP file when the template to be included is not under views folder?

like image 878
Rradhak Avatar asked May 07 '26 08:05

Rradhak


1 Answers

Yes, you can easily do that. Here you go:

import grails.gsp.PageRenderer

class MyLib {

    static namespace = "foo"
    static defaultEncodeAs = "raw"

    PageRenderer groovyPageRenderer

    def externalTemplate = { attrs, body ->
        String externalFilePath = attrs.externalPath

        /*
         * Put content of that external template to a file inside grails-app/views folder
         * with a temporary unique name appended by current timestamp
         */
        String temporaryFileName = "_external-" + System.currentTimeMillis() + ".gsp"

        File temporaryFile = new File("./grails-app/views/temp/$temporaryFileName")

        /*
         * Copy content of external file path to the temporary file in views folder.
         * This is required since the groovyPageRenderer can compile any GSP located inside
         * the views folder.
         */
        temporaryFile.text << new File(externalFilePath).text

        /*
         * Now compile the content of the external GSP code and render it
         */
        out << groovyPageRenderer.render([template: "/temp/$temporaryFileName", model: attrs.model])

        // Delete the file finally
        temporaryFile.delete()
    }
}

Now in your actual GSP where you want to include the external GSP, you can write so:

<body>
    <foo:externalTemplate externalPath="/home/user/anyExternalFile.gsp" model="${[status: 1}" />
</body>
like image 127
Shashank Agrawal Avatar answered May 11 '26 05:05

Shashank Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!