Add dirFiles Twig function

main
Anonymous Contributor 2023-09-02 15:33:21 +02:00
parent 595b4812e5
commit c70ae88a2a
2 changed files with 45 additions and 1 deletions

View File

@ -5,5 +5,14 @@ use Grav\Common\Theme;
class FourCreative extends Theme
{
// Access plugin events in this class
public static function getSubscribedEvents()
{
return ['onTwigExtensions' => ['onTwigExtensions', 0]];
}
public function onTwigExtensions()
{
require_once __DIR__.DIRECTORY_SEPARATOR.'php'.DIRECTORY_SEPARATOR.'DirFilesExtension.php';
$this->grav['twig']->twig->addExtension(new DirFilesExtension());
}
}

35
php/DirFilesExtension.php Normal file
View File

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Grav\Theme;
use Grav\Common\Twig\Extension\GravExtension;
class DirFilesExtension extends GravExtension
{
public function getName(): string
{
return 'DirFilesExtension';
}
public function getFunctions(): array
{
return [new \Twig_SimpleFunction('dirFiles', [$this, 'getDirFiles'])];
}
public function getDirFiles(string $dir, string $exts): array
{
$res = array();
$dir = '..'.DIRECTORY_SEPARATOR.(str_starts_with($dir, '/') ? substr($dir, 1) : $dir);
if (file_exists($dir) && $dirHandle = opendir($dir))
{
while ($entry = readdir($dirHandle)) {
if (preg_match('/^[a-zA-Z0-9-_][a-zA-Z0-9-_.]*\.('.$exts.')$/', $entry)) {
$res[] = $dir.DIRECTORY_SEPARATOR.$entry;
}
}
}
return $res;
}
}