Question: When outputting some UGC (`$user.text`) in a mako template, I'd like to sanitise the content using the mako filter 'h' and then add some `<br>` tags in place of newlines so there is a bit of formatting.

However, it appears that mako ignores the order that I apply the 'h' filter and now my `<br>` tags are being escaped and not rendered.

This is my br-adding filter:

```
<%
def nl2br(str):
    return str.replace("\n", "<br/>")
%>

```

This is my test string:

```
hello,

My name is

James

```

The following mako tags with filters:

```
${user.text | n,h,nl2br}
${user.text | n,nl2br,h}

```

... generate the same html with `<br>` tags escaped:

```
hello,
&lt;br/&gt;
&lt;br/&gt;My name is
&lt;br/&gt;
&lt;br/&gt;James

```

The only way I've been able to find to allow the `<br>` tags to come through without escaping is to remove the 'h' filter altogether as follows:

```
${user.text | n,nl2br}

```

But this defeats the object of sanitising the `user.text` field.

How can I get the 'h' filter to fire and then add `<br>` tags?

Am I missing something with buffers?

Answer: 
The behaviour you're seeing is due to the fact that `Markup.replace` assumes that the replacement string is unsafe:

```

>>> from markupsafe import Markup, escape
>>> e = escape(">x\ny")
>>> e
Markup(u'&gt;x\ny')
>>> e.replace("\n", "<br />")
Markup(u'&gt;x&lt;br /&gt;y')

```

The solution is to tell `markupsafe` that the `<br />` is trusted:

```

>>> e.replace("\n", Markup("<br />"))
Markup(u'&gt;x<br />y')

```

So your `nl2br` filter should be:

```
from markupsafe import Markup
def nl2br(s):
    return s.replace("\n", Markup("<br />"))

```

And then `${user.text|h,nl2br}` should work as expected.
I wasn't able to work out what's going on with the ordering above, so if you have the answer please post it here. Instead I used a workaround...

Since the `h` tag was firing too late in the filter order, I created my own version of it and forced it to return cleaned HTML by calling `__str__`.

```
def early_html_escape(string):
    """Run markupsafe escaping and force the result to string."""
    import markupsafe
    return markupsafe.escape(string).__str__()

```

This then allowed me to pass the user's text first through HTML escaping and then the `nl2br` filter, without the `<br>` tags being converted into HTML entities.

```
${user.text | early_html_escape,nl2br }

```

Hope that helps someone.