I’m using Twig in a standalone PHP app. So my composer only has this requirement: "twig/twig": "^3.6"
.
I initialize twig, and then add custom filter like so:
$loader = new TwigLoaderFilesystemLoader('templates');
$twig = new TwigEnvironment($loader, [
'cache' => 'tmp/cache',
]);
$twig->addFilter(new TwigTwigFilter('rot13', function ($string) {
return str_rot13($string);
}));
In my templates, I always get Unknown Filter error whenever I try to use the filter in {{ 'MYNAME' | rot13 }}
Also tried with Function, but getting similar Unknown Function error.
Am I missing something?
This is the error on the page:
Unknown "rot13" filter. [/myfiles/templates/tester.html:26]
[vendor/twig/twig/src/ExpressionParser.php:562] TwigExpressionParser->getFilterNodeClass('rot13',26)
[vendor/twig/twig/src/ExpressionParser.php:547] TwigExpressionParser->parseFilterExpressionRaw(TwigNodeExpressionConstantExpression::__set_state([]))
[vendor/twig/twig/src/ExpressionParser.php:405] TwigExpressionParser->parseFilterExpression(TwigNodeExpressionConstantExpression::__set_state([]))
[vendor/twig/twig/src/ExpressionParser.php:288] TwigExpressionParser->parsePostfixExpression(TwigNodeExpressionConstantExpression::__set_state([]))
[vendor/twig/twig/src/ExpressionParser.php:177] TwigExpressionParser->parsePrimaryExpression()
[vendor/twig/twig/src/ExpressionParser.php:72] TwigExpressionParser->getPrimary()
[vendor/twig/twig/src/Parser.php:127] TwigExpressionParser->parseExpression()
[vendor/twig/twig/src/TokenParser/ForTokenParser.php:42] TwigParser->subparse([TwigTokenParserForTokenParser::__set_state([]),'decideForFork'])
[vendor/twig/twig/src/Parser.php:170] TwigTokenParserForTokenParser->parse(TwigToken::__set_state([]))
[vendor/twig/twig/src/TokenParser/BlockTokenParser.php:47] TwigParser->subparse([TwigTokenParserBlockTokenParser::__set_state([]),'decideBlockEnd'],true)
[vendor/twig/twig/src/Parser.php:170] TwigTokenParserBlockTokenParser->parse(TwigToken::__set_state([]))
[vendor/twig/twig/src/Parser.php:83] TwigParser->subparse(NULL,false)
[vendor/twig/twig/src/Environment.php:491] TwigParser->parse(TwigTokenStream::__set_state([]))
[vendor/twig/twig/src/Environment.php:519] TwigEnvironment->parse(TwigTokenStream::__set_state([]))
[vendor/twig/twig/src/Environment.php:351] TwigEnvironment->compileSource(TwigSource::__set_state([]))
[vendor/twig/twig/src/Environment.php:312] TwigEnvironment->loadTemplate('__TwigTemplate_9fcd4d27f601c5dddfd436979e4446b0','admin/classlist.html')
2
Answers
User error. There were two
$twig
instances, filters were added to one instance and rendered using the other one. Thanks to @DarkBee for asking the right question :-)Try
Maybe he’s just not able to resolve the class path. Works in my environment