Twig nl2br filter not working on entity

nl2br, php, symfony, template-engine, twig

Solution

Instead of having:

$result .= '\n' . $this->getZipCode().' '.$this->getCity();

try this:

$result .= "\n" . $this->getZipCode()." ".$this->getCity();

PHP will interpret escape characters in double quoted strings.

This PHP Manual page might help.

Problem

I have an Address entity with a __toString() method like this : ``` public function __toString() { $result = $this->getStreet(); if ($this->getStreet2()) $result .= '\n' . $this->getStreet2(); $result .= '\n' . $this->getZipCode().' '.$this->getCity(); return $result; } ``` In my template, I apply the Twig nl2br filter on the entity : ``` {{ user.address|nl2br }} ``` but I still get the escaped \n : 1107 West Adams Boulevard\n90007 Los Angeles, CA I tried using this string instead of the entity : ``` {{ "1107 West Adams Boulevard\n90007 Los Angeles, CA"|nl2br }} ``` And I get the expected result : 1107 West Adams Boulevard 90007 Los Angeles, CA I also tried ``` {{ user.address|raw|nl2br }} ``` Which is not safe, but still doesn't work... I've tried with Twig 1.8.0 and 1.9.0. Any idea ?

Original source