问题
I want to determine if my key is an object:
{% for key in columns %}
{% if key is object %}
This is an object
{% else %}
This in not an object
{% endif %}
{% endfor %}
But I get the error message:
Unknown "object" test.
回答1:
You can create your own Twig extension. I see you've tagged your question with Symfony so assuming you use Twig in Symfony, you can follow this tutorial:
https://symfony.com/doc/3.4/templating/twig_extension.html
What you need to do is add new TwigTest
based on this example:
https://twig.symfony.com/doc/2.x/advanced.html#tests
You should end up with something like this:
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigTest;
class AppExtension extends AbstractExtension
{
public function getTests()
{
return array(
new TwigTest('object', array($this, 'isObject')),
);
}
public function isObject($object)
{
return is_object($object);
}
}
Code above is not tested, but should work fine.
来源:https://stackoverflow.com/questions/53675244/how-can-i-determine-if-key-is-an-object-twig