dopatraman
dopatraman

Reputation: 13908

Write all files in a directory to .gsp page

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

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

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:

  1. new File(path) - Create a Java File object to represent the directory path.
  2. .listFiles() - Returns a list of all files and directories (excluding sub-directories) each represented by File objects.
  3. *.path - A spread operator expression which returns a list of file path Strings, effectively converting the File objects into Strings. It's the equivalent of .collect { it.path }.

Upvotes: 1

Related Questions