Skip to research

Creer un custom filtre pour Twig - Drupal 8

Temps de lecture
Moins d'une minute
Étiquettes

Créons un custom filtre pour twig dans drupal 8.

Dans un custom module, créer un service
mon_custom_module.services.yml

services:
  mon_custom_module.twig_extension:
    arguments: ['@renderer']
    class: Drupal\mon_custom_module\TwigExtension\AddSpecialCaractereExtention
    tags:
      - { name: twig.extension }


Créer la class AddSpecialCaractere
src/TwigExtension/AddSpecialCaractereExtention .php

<?php
namespace Drupal\mon_custom_module\TwigExtension;
 
 
class AddSpecialCaractereExtention extends \Twig_Extension {    
 
  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('specialcaractere', array($this, 'specialCaractere')),
    ];
  }
 
  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'AddSpecialCaractere.twig_extension';
  }
 
  /**
   * Add your special caractere to string
   */
  public static function specialCaractere($string, $caractere) {
    return $caractere . '' . $string;
  }
 
}

 

Dans vos fichiers Twig, il est possible d'appeler la fonction.

{{ 'TontonTristan'| specialcaractere('@') }}

@TontonTristan