Filtering @getFilesAtPath results in Docpad

272 Views Asked by At

In Docpad, the following code (using a Query-Engine helper and eco) pulls a list of file names from a directory tree and addds their url to an array:

<% images = []; %>
<% for file in @getFilesAtPath({relativeOutDirPath: 'images/'}).toJSON() : %>
    <% images.push(file.url) %>
<% end %>

How might I limit the query to a subset of files, say only PNGs?

1

There are 1 best solutions below

0
On BEST ANSWER

So like stated in my answer to your other question: What methods can be called on Docpad's Query tools?

Object returned by your query has some additional default metadata you can't see. As you can see here http://docpad.org/docs/meta-data, one of the metadata is "extension". So you can query with condition like:

extension:'png'

So your code might look like (notice findAll part that gives you a possibility to set search condidtions):

<% images = []; %>
<% for file in @getFilesAtPath({relativeOutDirPath: 'images/'}).findAll(extension:'png').toJSON() : %>
    <% images.push(file.url) %>
<% end %>

Or if you want to return all files and trigger different actions on different extensions you could:

<% images = []; %>
<% for file in @getFilesAtPath(relativeOutDirPath: 'images/').toJSON() : %>
    <% if file.extension is 'png' : %>
        <% images.push(file.url) %>
    <% end %>
<% end %>