0

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.

dopatraman
  • 13,416
  • 29
  • 90
  • 154
  • Does [this post](http://stackoverflow.com/questions/3953965/groovy-get-a-list-of-all-the-files-in-a-directory-recursive) help? – Mike B Aug 14 '16 at 07:12

1 Answers1

1

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 }.
Emmanuel Rosa
  • 9,697
  • 2
  • 14
  • 20