Retrieving filtered list of files using template toolkit

159 views Asked by At

I would like to retrive the content of files in a directory, which fulfill a given regexp rule or string (e.g. ./*.xml).

I found following example

[% FOREACH directory.files.grep('\.txt$') %]
   ...
[% END %]

but do not know how to use it. Could this solve my problem?

1

There are 1 answers

1
RET On BEST ANSWER

A quick look at the documentation suggests that the output of directory.files is a collection of objects, so .grep() is unlikely to work. It has methods like name, isdir and so on.

The simplest solution would be something like:

[%- FOREACH file IN directory.files;
        #NEXT UNLESS file.name.match('\.xml$');
        NEXT UNLESS file.ext == 'xml';
        ...
    END -%]

Edit: improved answer based on suggestion by ThisSuitIsBlackNot.