<?php
use Twig\Extension\AbstractExtension;
use Twig\Node\Expression\Binary\AbstractBinary;
use Twig\Compiler;
// creating Twig Tag as Extension
class MyTwigOperators extends AbstractExtension
{
public function getName()
{
return 'MyOperators';
}
public function getOperators()
{
return [
[], // unary operator.
[ // binary operator
'isIn' => [
'class' => 'IsIn',
'precedence' => 20,
'associativity' => Twig\ExpressionParser::OPERATOR_LEFT,
],
]];
}
}
class IsIn extends AbstractBinary
{
public function compile(Compiler $compiler) : void
{
$compiler
->raw('(in_array(')
->subcompile($this->getNode('left'))
->raw(', ')
->subcompile($this->getNode('right'))
->raw('))')
;
}
public function operator(Compiler $compiler) : Compiler
{
return $compiler->raw('');
}
}
$path = __DIR__ . '/templates/';
$file = 'operator.html.twig';
echo '<b>- template content:</b>' . PHP_EOL;
echo file_get_contents($path . $file) . PHP_EOL;
$loader = new Twig\Loader\FilesystemLoader($path);
$twig = new Twig\Environment($loader);
$twig->addExtension(new MyTwigOperators());
echo '<b>- rendered template:</b>' . PHP_EOL;
echo $twig->render($file);
Result
- template content:
{% set needle = "foo" %}
{% set haystack1 = ["bar","baz"] %}
{% set haystack2 = ["bar","foo","baz"] %}
haystack1:
{% if needle isIn haystack1 %}
it is in array 1
{% endif %}
haystack2:
{% if needle isIn haystack2 %}
it is in array 2
{% endif %}
- rendered template:
haystack1:
haystack2:
it is in array 2