Twig : Unescape hexadecimal text

1.3k views Asked by At

I try to secure email address on my website and I used the function (twig filter) below to encode it :

/**
 * The twig filter associated with this function is "encode_email"
 */
function encode_emailFilter($email) 
{ 
    $text = $email; 
    $text_encode = ''; 

    for ($x=0; $x < strlen($text); $x++) { 
        $text_encode .= '&#x' . bin2hex($text[$x]).';'; 
    } 

    return $text_encode; 
} 

So, I encoded my email like this

{{ emailFromDatabase|encode_email }}

And on my HTML page, it shows

&#x73;&#x75;&#x70;&#x65;&#x72;&#x6d;&#x61;&#x72;&#x69;&#x6f;&#x40;&#x67;&#x6d;&#x61;&#x69;&#x6c;&#x2e;&#x63;&#x6f;&#x6d;

I tried to add "raw" to the filter but, I always get the same result

{{ emailFromDatabase|raw|encode_email }}

However, if I display directly the hexadecimal without wrapping it with {{ }}, the email address displays correctly

<span>&#x73;&#x75;&#x70;&#x65;&#x72;&#x6d;&#x61;&#x72;&#x69;&#x6f;&#x40;&#x67;&#x6d;&#x61;&#x69;&#x6c;&#x2e;&#x63;&#x6f;&#x6d;</span>

//Returns
[email protected]

So, what filter should I add to my twig variable to get it work?

Thanks in advance for your answers

1

There are 1 answers

1
Jasper N. Brouwer On BEST ANSWER

You'll need to put raw at the end:

{{ emailFromDatabase|encode_email|raw }}

Because you want:

  • to take the variable
  • encode it
  • then display it without escaping