lelyfoto / twig-instanceof

Adds InstanceOf Expression as Twig Extension
MIT License
3 stars 3 forks source link
bundle instanceof php symfony symfony-bundle twig

Twig InstanceOf Expression

Package version PHP version License

Adds InstanceOf Expression as Twig Extension. When you want to check for a specific type of variable in a twig template.

Prerequisites

Installation

  1. Install this Symfony bundle with composer:
    composer require lelyfoto/twig-instanceof
  2. Make sure the bundle is added to config/bundles.php:
    return [
        // ...
        Lelyfoto\Twig\InstanceOf\TwigInstanceOfBundle::class => ['all' => true],
        // ...
    ];   

Usage

Important to note that when testing for a class that you must use quotes and escaping inside the twig templates.

{% if testObject is instanceof('\\Example\\TestInterface') %}
    Do something with {{ testObject.show() }}
{% endif %}

Use without Symfony

use Twig\Environment;
use Lelyfoto\Twig\InstanceOf\InstanceOfExtension;

$twig = new Environment($loader);
$twig->addExtension(new InstanceOfExtension());