Skip to content

Instantly share code, notes, and snippets.

@hadl
Last active May 27, 2021 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadl/82ba9b1a8088570163e813a594cfa5d0 to your computer and use it in GitHub Desktop.
Save hadl/82ba9b1a8088570163e813a594cfa5d0 to your computer and use it in GitHub Desktop.
patternlab node - engine-twig-php extend/alter twig
<?php
/**
* @param Twig_Environment $env - The Twig Environment - https://twig.symfony.com/api/1.x/Twig_Environment.html
* @param $config - Config of `@basalt/twig-renderer`
*/
function addCustomExtension(\Twig_Environment &$env, $config) {
$env->addExtension(new \Twig_Extension_Debug());
/**
* ADD TWIG EXTENDS FROM FOLDER
*/
try {
$functionsDir = __DIR__ . DIRECTORY_SEPARATOR . '_functions';
$filtersDir = __DIR__ . DIRECTORY_SEPARATOR . '_filters';
if ($handle = opendir($functionsDir)) {
while (false !== ($fileName = readdir($handle))) {
if ($fileName[0] != "_" && $fileName[0] != "." && substr_count(
$fileName,
'.function.php'
)) {
include($functionsDir . DIRECTORY_SEPARATOR . $fileName);
// $function should be defined in the included file
if (isset($function)) {
$env->addFunction($function);
unset($function);
}
}
}
}
if ($handle = opendir($filtersDir)) {
while (false !== ($fileName = readdir($handle))) {
if ($fileName[0] != "_" && $fileName[0] != "." && substr_count($fileName, '.filter.php')) {
include($filtersDir . DIRECTORY_SEPARATOR . $fileName);
// $filter should be defined in the included file
if (isset($filter)) {
$env->addFilter($filter);
unset($filter);
}
}
}
}
// echo '--- ADDED TWIG EXT IN ' . (microtime(true) - $time) . 'ms' . PHP_EOL;
} catch (Exception $e) {
echo $e . PHP_EOL;
}
}
// patternlab config for basalt/twig-renderer to include the alter-twig.php file
{
....
"engines": {
"twig": {
"namespaces": [
....
],
"alterTwigEnv": [
{
"file": "source/_twig/alter-twig.php",
"functions": [
"addCustomExtension"
]
}
]
}
}
}
<?php
// put this file in the _filters folder next to alter-twig.php
// trans filter is context aware, so it will pick up "keys" from the patternlab data.json files too
$filter = new Twig_SimpleFilter(
'trans',
function ($context, $string) {
if (array_key_exists($string, $context)) {
return $context[$string];
}
return $string;
},
[
'needs_context' => true,
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment