3

I have used the pyramid framework to build a large web application.

Among other things, this application allows the user to enter text into a text area form field. This text is then saved to a database and of course can be readout again and displayed later.

To display content I am using the Chameleon Template Engine.

This works fine, except that line breaking is not displayed correctly (not displayed at all). This is probably due to the fact that the newlines entered into the text area do not cause a new line in HTML when displayed through Chameleon. How can one fix this?

It does not help to replace the newlines by <br>-Tags because by default Chameleon escapes all HTML-Tags. I am aware of the fact that one can deactivate this feature, but I do not want to do that to avoid cross-site scripting.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Meneldur
  • 215
  • 1
  • 5

2 Answers2

2

You need to break the text into separate lines, then render this using a loop and <br/> tags:

<span tal:omit-tag="" 
      tal:repeat="line text_with_newlines.splitlines()">
  ${line}<br />
</span>

This uses the str.splitlines() method to split the text on newlines, then the loop adds a <br /> break tag after each line of the text.

You are quite right not doing this in the view, then forcing Chameleon to accept your inserted <br /> tags by setting the structure: flag. Luckily there is absolutely no need for that anyway.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Another possibility is to do something like the following:

import webhelpers.html.tags as t
s = t.literal(t.BR).join(s.split(t.NL))

You can of course create a helper function from it.

born
  • 656
  • 1
  • 6
  • 21
  • The problem with this approach is that you then have to switch off the automatic HTML escaping Chameleon does; you'd have to first escape `s` manually, then turn newlines into break tags, then interpolate the result using the `structure:` switch. The OP rightfully doesn't want to do this; there are always risks when you do the escaping yourself. – Martijn Pieters Feb 24 '13 at 11:54
  • 1
    no, you don't need to add `structure:` when you output an object of type t.literal (see http://sluggo.scrapping.cc/python/WebHelpers/modules/html/builder.html) – born Feb 24 '13 at 12:59
  • The OP is asking for something to use in *chameleon* here. – Martijn Pieters Feb 24 '13 at 13:17