peace_love
peace_love

Reputation: 6471

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

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.

Upvotes: 0

Views: 1559

Answers (2)

Julien ZB
Julien ZB

Reputation: 31

An easy way to check if a variable is an object or a string :

{% if var.id|default('') is not same as ('') %}

Upvotes: 2

cadavre
cadavre

Reputation: 1394

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.

Upvotes: 3

Related Questions