Reputation: 13908
Lets say I have a gsp page that I want to load all the scripts in a particular folder:
<html>
<head>
{each file in $path}
<asset:javascript src="file" />
</head>
</html>
assuming $path
is a directory path. Most templating languages have a way to do this so I'm sure Grails can accomplish it. But I'm not sure how to make it happen. My end goal is this:
ndex
<html>
<head>
<asset:javascript src="js/util.js" />
<asset:javascript src="js/util2.js" />
<asset:javascript src="js/index.js" />
</head>
</html>
Please help.
Upvotes: 0
Views: 167
Reputation: 9885
You can do something like this:
<html>
<head>
<g:each var="file" in="${(new File(path)).listFiles()*.path}">
<asset:javascript src="${file}" />
</g:each>
</head>
</html>
The GSP g:each tag is how iteration is performed in Grails when using GSP. The in attribute is used to specify the Iterable
to iterate through. In this case it's the expression:
(new File(path)).listFiles()*.path
The expression means:
new File(path)
- Create a Java File
object to represent the directory path..listFiles()
- Returns a list of all files and directories (excluding sub-directories) each represented by File
objects.*.path
- A spread operator expression which returns a list of file path String
s, effectively converting the File
objects into String
s. It's the equivalent of .collect { it.path }
.Upvotes: 1