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;
class CustomModuleExtensionAdapter extends AbstractExtension
{
public function __construct() {
CustomModuleExtensionLoader::init();
}
public function getFunctions() {
return CustomModuleExtensionLoader::getFunctions();
}
public function getFilters() {
return CustomModuleExtensionLoader::getFilters();
}
}
CustomModuleExtensionLoader.php
namespace Drupal\custom_module\TwigExtension;
class CustomModuleExtensionLoader
{
public static $functions = [];
public static $filters = [];
public static function init() {
if (!self::$functions) {
static::loadAllFunctions();
}
if (!self::$filters) {
static::loadAllFilters();
}
}
public static function getFunctions() {
return !empty(self::$functions) ? self::$functions : [];
}
public static function getFilters() {
return !empty(self::$filters) ? self::$filters : [];
}
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);
}
}
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);
}
}
protected static function load(string $file, array &$collection) {
$function = NULL;
if (file_exists($file)) {
include $file;
$collection[] = $function;
}
}
}