Introduction
GetFiles was first launched in February 2019. It retrieves a list of files from a specified folder.
Requirements
- Craft 3.1 or above
- You need a simple way of retrieving files which are not managed by Craft
Examples
List the contents of a directory
Inside /assets/images there are 3 image files:
22 Apr 22:54 image01.jpg
22 Apr 22:54 image02.jpg
22 Apr 22:54 image03.gif
In Twig we pass an array of settings into GetFiles. The settings array contains the path of the folder to list:
{% set settings =
{
path: '/assets/images/'
}
%}
{% set images = craft.getfiles.config(settings) %}
<p>Available images:</p>
{% for image in images %}
<img src="{{ image }}" alt="Image {{ loop.index }}">
{% endfor %}
This would output:
<img src="/assets/images/image01.jpg" alt="Image 1">
<img src="/assets/images/image02.jpg" alt="Image 2">
<img src="/assets/images/image03.gif" alt="Image 3">
List the contents of a directory which matches a regex pattern
Inside /assets/images there are 3 files:
22 Apr 22:54 image01.jpg
22 Apr 22:54 image02.jpg
22 Apr 22:54 image03.gif
In Twig we pass an array of settings into GetFiles. The settings array contains the path of the folder to list and a regex pattern to match:
{% set settings =
{
path: '/assets/images/',
pattern: '*.gif'
}
%}
{% set images = craft.getfiles.config(settings) %}
<p>Available images:</p>
{% for image in images %}
<img src="/assets/images/{{ image }}" alt="Image {{ loop.index }}">
{% endfor %}
This would output:
<p>Available images:<p>
<img src="/assets/images/image03.gif" alt="Image 1">
Configuration
path
string, required
A valid folder for GetFiles to search
pattern
string, optional, default value '*'
A regex pattern to match
pathformat
string, optional, default value '2'
- Filename only
- Filename relative to your base path (default value)
- Absolute path to the filename
{% set myVarSettings =
{
path: '<path>',
pathformat: '<pathformat>',
pattern: '<pattern>'
}
%}
{% set myVar = craft.getfiles.config(myVarSettings) %}
Installation
composer require youandmedigital/craft-getfiles
If you have any issues, feedback or ideas, please feel free to submit an issue on Github.
Read this next