Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof operator in Twig/Symfony 2?

Tags:

twig

symfony

I've a mixed array like this one (mobile numbers and entities):

$targets = array();

$targets[] = '+32647651212';
$targets[] = new Customer();

In my Twig template i have to call getMobile() if target is a Customer or just print the number if it's actually a number (string).

Is there something like instanceof operator in Twig?

<ul>
{% for target in targets %}
   <li>{{ target instance of MyEntity ? target.getMobile : target }}</li>
   {% else %}
       <li>Nothing found.</li>
</ul>
like image 247
gremo Avatar asked May 28 '12 17:05

gremo


2 Answers

In \Twig_Extension you can add tests

public function getTests()
{
    return [
        'instanceof' =>  new \Twig_Function_Method($this, 'isInstanceof')
    ];
}

/**
 * @param $var
 * @param $instance
 * @return bool
 */
public function isInstanceof($var, $instance) {
    return  $var instanceof $instance;
}

And then use like

{% if value is instanceof('DateTime') %}
like image 184
valdas.mistolis Avatar answered Sep 27 '22 18:09

valdas.mistolis


UPDATE 10-2021

Please be aware this answer has been written for symfony 3, and twig 2. If you use a more recent version, please refer to the answer of @Garri Figueroa on this post.

As you can see in the twig documentation the class \Twig_Extension, \Twig_SimpleTest are now deprecated.

If you use a more recent version of symfony (I recommend it), please use the new class AbstractExtension, TwigFunction, etc https://symfony.com/doc/5.3/templating/twig_extension.html


OLD VERSION : symfony 3.4

Here a nice way to do instanceof operator in twig with Extension :

1) Create your extention file where you want

(ex: src/OC/YourBundle/Twig/InstanceOfExtension.php )

With \Twig_Extension you can do many things, filter, fonction, but now we will create a Test.

So we implement function getTests(), and inside it we create a new \Twig_SimpleTest

The 1st arugment is the name of test you create, and the seconde a callable. (can be a function() {}).

<?php

namespace OC\YourBundle\Twig;

class InstanceOfExtension extends \Twig_Extension {

    public function getTests() {
        return array(
            new \Twig_SimpleTest('instanceof', array($this, 'isInstanceOf')),
         );
     }

    public function isInstanceOf($var, $instance) {
        $reflexionClass = new \ReflectionClass($instance);
        return $reflexionClass->isInstance($var);
    }
}

2) Register it in services.yml

(ex: src/OC/YourBundle/Resources/config/services.yml)

services:

    [...may you have other services ...]

    app.twig_extension:
        class: OC\YourBundle\Twig\InstanceOfExtension
        public: false
        tags:
          - { name: twig.extension }

3) Then use it in twig like this

{{ myvar is instanceof('\\OC\\YourBundle\\Entity\\YourEntityOrWhatEver') }}

Source from Adrien Brault => https://gist.github.com/adrienbrault/7045544

like image 21
Zombkey Avatar answered Sep 27 '22 16:09

Zombkey