{ Twig Extension – HTML Entity Decode }

This is a custom Twig filter to enable the use of PHP’s html_entity_decode() function in Twig.

Assuming a custom module name of example_module:

modules/custom/example_module/src/TwigExtension

EntityDecoderExtension.php

namespace Drupal\example_module\TwigExtension;

use Drupal\Core\Template\TwigExtension;

class EntityDecoderExtension extends TwigExtension {

  /**
   * @return string
   */
  public function getName() {
    return 'entitydecoder.twig_extension';
  }

  /**
   * @return array
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('html_entity_decode', [$this, 'filterEntityDecode'])
    ];
  }

  /**
   * @param $html
   * @return string
   */
  public static function filterEntityDecode($html) {
    return html_entity_decode($html);
  }
}

Then we’ll need a services file.

modules/custom/example_module

example_module.services.yml

services:
  entitydecoder.twig_extension:
    arguments: ['@renderer', '@url_generator', '@theme.manager', '@date.formatter']
    class: Drupal\example_module\TwigExtension\EntityDecoderExtension
    tags:
      - { name: twig.extension }

 

Then we apply it to a Twig field that may not encode & / & properly:

{{ content.field_name | html_entity_decode }}