Search code examples
twig

Twig uses htmlspecialchars internally for escaping. How do I pass ENT_NOQUOTES?


I'm using Twig for an embedded application that renders a basic subset of HTML. However, it does not support " for double quotes, and simply shows quot; instead of ".

A screen with misrendered HTML entities

I want to achieve the equivalent of

htmlspecialchars($input_string, ENT_NOQUOTES);

Twig's documentation says that it uses htmlspecialchars internally for its escaping. How do I set this flag when escaping a particular string?


Solution

  • Use a custom escaping strategy.

    Create a new escaping strategy called html_no_quotes as follows:

    $twig
        ->getExtension(\Twig\Extension\CoreExtension::class)
        ->setEscaper('html_no_quotes', function($twig_environment, $string, $charset) {
            return htmlspecialchars($string, ENT_NOQUOTES);
        })
    ;
    

    Then inside your template use your html_no_quotes escaping strategy as follows:

    {{ someString | escape('html_no_quotes') }}