Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting \n to <br> in mako files

I'm using python with pylons

I want to display the saved data from a textarea in a mako file with new lines formatted correctly for display

Is this the best way of doing it?

> ${c.info['about_me'].replace("\n", "<br />") | n}
like image 227
Joe Gibbons Avatar asked Dec 23 '22 05:12

Joe Gibbons


1 Answers

The problem with your solution is that you bypass the string escaping, which can lead to security issues. Here is my solution :

<%! import markupsafe %>
${text.replace('\n', markupsafe.Markup('<br />'))}

or, if you want to use it more than once :

<%!
    import markupsafe
    def br(text):
        return text.replace('\n', markupsafe.Markup('<br />'))
%>
${text | br }

This solution uses markupsafe, which is used by mako to mark safe strings and know which to escape. We only mark <br/> as being safe, not the rest of the string, so it will be escaped if needed.

like image 54
madjar Avatar answered Dec 31 '22 13:12

madjar