How can I determine if key is an object (twig)?

会有一股神秘感。 提交于 2021-02-11 12:32:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!