Skip to main content
Development

Introducing GetAsset for Craft CMS

Posted: 18 May 2020. Updated: 27 May 2020

This utility plugin looks inside a folder for a file that was last modified and returns the value in Twig.

Introduction

GetAsset was first launched in February 2019. It looks inside a folder for a file that was last modified and returns the value in Twig.

Requirements

  • Craft 3.1 or above

Examples

Return the last modified file from a directory

Folder path /assets/css contains 3 files, with the following timestamps:

22 Apr 22:54 c.min.d6df804850.css
22 Apr 22:55 plugin.css
22 Apr 22:54 ie.min.8af08fe73b.css
COMMAND LINE

In Twig we pass an array of settings into GetAsset:

{% set settings =
    {
        path: '/assets/css/'
    }
%}
{% set file = craft.getasset.config(settings) %}
<link rel="stylesheet" href="/assets/css/{{ file }}">
TWIG

This would output:

<link rel="stylesheet" href="/assets/css/plugin.css">
HTML

Return the last modified file from a directory that matches a regex pattern

Folder path /assets/css contains 4 files, with the following timestamps:

22 Apr 22:54 c.min.d6df804850.css
22 Apr 22:50 c.min.a8xd808007.css
22 Apr 22:55 p.min.d6df804850.css
22 Apr 22:54 ie.min.8af08fe73b.css
COMMAND LINE

In Twig we pass an array of settings into GetAsset. The settings array contains the path and regex pattern:

{% set settings =
    {
        path: '/assets/css/',
        pattern: '/^(c).min.*\\S{10}.css$/'
    }
%}
{% set file = craft.getasset.config(settings) %}  
<link rel="stylesheet" href="/assets/css/{{ file }}">
TWIG

This example Twig code would output:

<link rel="stylesheet" href="/assets/css/c.min.d6df804850.css">
HTML

Configuration

path

string, required

A valid folder for GetAsset to search

pattern

string, optional, default value '*'

A regex pattern to match

{% set myVarSettings =
    {
        path: '<path>',
        pattern: '<pattern>'
    }
%}
{% set myVar = craft.getasset.config(myVarSettings) %}
TWIG

Installation

composer require youandmedigital/craft-getasset
COMMAND LINE

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

Read this next

Weeknote #4

Weeknote #4 for the week ending 17th May 2020.

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

Ready to discuss your next project?