Using the asset pipeline Grails plugin to write Page-Specific Javascript

Biniam Asnake
Feb 27, 2021

The Grails Asset-Pipeline is a plugin used for managing and processing static assets in Grails applications.
Asset-Pipeline functions include processing and minification of both CSS and JavaScript files. It is also capable of being extended to compile custom static assets, such as CoffeeScript or LESS.
Here is one way of using the asset pipeline grails plugin to write Page-Specific Javascript.

specific.js // will be included by default

var pageSpecific = function() { 
console.log('Hello from specific page!)
});
$(document).ready(function({
if($(document.body).data('page') == 'specific') {
pageSpecific())
}
}));

index.gsp

<meta name='layout' content='main'/>  
<body data-page="specific">
<h1>Hello from Specific!</h1>
</body>

Modify `main.gsp` so that it passes the data-page attribute to the JS (since `index.gsp` uses `main` as a layout)

main.gsp

<body data-page"${pageProperty(name:'body.data-page')}">  
// main body content
</body>

Originally published at http://binyit.blogspot.com.

--

--