Twig nl2br filter not working on entity
Asked Answered
B

1

5

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 ?

Bankston answered 21/7, 2012 at 16:59 Comment(1)
Use "\n" instead of '\n' :)Voluble
C
15

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.

Carthy answered 21/7, 2012 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.