I’ve a small twig custom filter in my project created following https://symfony.com/doc/current/templating/twig_extension.html . As long as it sits in src/Twig
, it works as expected.
Now I’m trying to move it to a custom bundle (vendor/turbolabit/tli-base-bundle/src/Twig/
) to make it reusable.
I moved the two files:
<?php namespace TurboLabItTLIBaseBundleTwig; use AppTwigAppRuntime; use TwigExtensionAbstractExtension; use TwigTwigFilter; class TrimmerExtension extends AbstractExtension { public function getFilters() { return [ new TwigFilter('trimmer', [TrimmerExtensionRuntime::class, 'trim']), ]; } }
<?php namespace TurboLabItTLIBaseBundleTwig; use TwigExtensionRuntimeExtensionInterface; class TrimmerExtensionRuntime implements RuntimeExtensionInterface { public function trim(string $value): string { return trim($value); } }
I tagged it in services.yaml
:
TurboLabItTLIBaseBundleTwigTrimmerExtension: tags: [twig.runtime]
(I also tried as tags: [twig.extension]
, even if it would be incorrect because this is a lazy-loaded filter, but it makes no difference)
I see it in symfony console debug:twig --filter=trimmer
:
Filters ------- * trimmer
But when I try to use it (like I did before):
<div>{% apply trimmer %} this must be trimmed {% endapply %}</div>
it explodes:
Unable to load the “TurboLabItTLIBaseBundleTwigTrimmerExtensionRuntime” runtime.
What am I missing?
Advertisement
Answer
It is difficult to understand exactly how this should be configured from the docs. The way I understand it the TrimmerExtension
should be tagged extension
and/or the TrimmerExtensionRuntime
should get the runtime
tag.
TurboLabItTLIBaseBundleTwigTrimmerExtension: tags: [twig.extension] TurboLabItTLIBaseBundleTwigTrimmerExtensionRuntime: tags: [twig.runtime]