May 18th, 2021

Creating custom Twig functions and filters

custom_module.services.yml

services:
custom_module.custom_module_twig_extensions:
arguments: ['@renderer']
class: Drupal\custom_module\TwigExtension\CustomModuleExtensionAdapter
tags:
- { name: twig.extension }

CustomModuleExtensionAdapter.php

namespace Drupal\custom_module\TwigExtension;
use Twig\Extension\AbstractExtension;
/**
* Collect custom twig functions and filters
*/
class CustomModuleExtensionAdapter extends AbstractExtension
{
/**
* CustomModuleExtensionAdapter constructor.
*/
public function __construct() {
CustomModuleExtensionLoader::init();
}
/**
* Get all Twig functions.
*/
public function getFunctions() {
return CustomModuleExtensionLoader::getFunctions();
}
/**
* Get all Twig filters.
*/
public function getFilters() {
return CustomModuleExtensionLoader::getFilters();
}
}

CustomModuleExtensionLoader.php

namespace Drupal\custom_module\TwigExtension;
/**
* Load individual extensions
*/
class CustomModuleExtensionLoader
{
/**
* Set of Twig functions
*
* @var array
*/
public static $functions = [];
/**
* Set of Twig filters
*
* @var array
*/
public static $filters = [];
/**
* Calls loader for Twig helpers
*/
public static function init() {
if (!self::$functions) {
static::loadAllFunctions();
}
if (!self::$filters) {
static::loadAllFilters();
}
}
/**
* Get all Twig functions
*/
public static function getFunctions() {
return !empty(self::$functions) ? self::$functions : [];
}
/**
* Get all Twig filters
*/
public static function getFilters() {
return !empty(self::$filters) ? self::$filters : [];
}
/**
* Load all Twig functions
*/
protected static function loadAllFunctions() {
$fullPath = drupal_get_path('module', 'custom_module') . '/twig-components/functions/';
if (is_dir($fullPath)) {
static::load($fullPath . 'add_attributes.function.drupal.php', self::$functions);
static::load($fullPath . 'svg_icon.function.drupal.php', self::$functions);
}
}
/**
* Load all Twig filters
*/
protected static function loadAllFilters() {
$fullPath = drupal_get_path('module', 'custom_module') . '/twig-components/filters/';
if (is_dir($fullPath)) {
static::load($fullPath . 'unique_id.filter.drupal.php', self::$filters);
}
}
/**
* Load a single Twig dependency
*
* @param string $file
* @param array $collection
*/
protected static function load(string $file, array &$collection) {
$function = NULL;
if (file_exists($file)) {
include $file;
$collection[] = $function;
}
}
}