Skip to content

Commit

Permalink
Add TwigTypeCastingExtension
Browse files Browse the repository at this point in the history
Useful for casting variables in Twig
  • Loading branch information
slawkens committed Apr 8, 2024
1 parent 8b0b123 commit 7181b98
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
36 changes: 36 additions & 0 deletions system/libs/TwigTypeCastingExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace MyAAC\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

final class TwigTypeCastingExtension extends AbstractExtension
{
/** @return array<int, TwigFilter> */
public function getFilters(): array
{
return [
new TwigFilter('int', function ($value) {
return (int)$value;
}),
new TwigFilter('float', function ($value) {
return (float)$value;
}),
new TwigFilter('string', function ($value) {
return (string)$value;
}),
new TwigFilter('bool', function ($value) {
return (bool)$value;
}),
new TwigFilter('array', function (object $value) {
return (array)$value;
}),
new TwigFilter('object', function (array $value) {
return (object)$value;
}),
];
}
}
3 changes: 3 additions & 0 deletions system/twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
}
unset($dev_mode);

require LIBS . 'TwigTypeCastingExtension.php';
$twig->addExtension(new MyAAC\Twig\Extension\TwigTypeCastingExtension());

$function = new TwigFunction('getStyle', function ($i) {
return getStyle($i);
});
Expand Down

0 comments on commit 7181b98

Please sign in to comment.