Skip to main content
Development

Introducing GetFiles for Craft CMS

Posted: 11 May 2020. Updated: 27 May 2020

This little utility plugin retrieves a list of files from a specified folder.

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
COMMAND LINE

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 %}
TWIG

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">
HTML

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
COMMAND LINE

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 %}
TWIG

This would output:

<p>Available images:<p>
<img src="/assets/images/image03.gif" alt="Image 1">
HTML

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' 
  1. Filename only
  2. Filename relative to your base path (default value)
  3. Absolute path to the filename
{% set myVarSettings =
    {
        path: '<path>',
        pathformat: '<pathformat>',
        pattern: '<pattern>'
    }
%}

{% set myVar = craft.getfiles.config(myVarSettings) %}
TWIG

Installation

composer require youandmedigital/craft-getfiles
COMMAND LINE

If you have any issues, feedback or ideas, please feel free to submit an issue on Github.

Read this next

Weeknote #3

Weeknote #3 for the week ending 10th May 2020.

  1. Home
  2. Notes
  3. Introducing GetFiles for Craft CMS
Illustration of Jon Leverrier

Ready to discuss your next project?