views:

233

answers:

3

I'm trying to output the content of a comment with genshi, but I can't figure out how to transform the newlines into HTML paragraphs.

Here's a test case of what it should look like:

input: 'foo\n\n\n\n\nbar\nbaz'

output: <p>foo</p><p>bar</p><p>baz</p>

I've looked everywhere for this function. I couldn't find it in genshi or in python's std lib. I'm using TG 1.0.

+2  A: 

There may be a built-in function in Genshi, but if not, this will do it for you:

output = ''.join([("<p>%s</p>" % l) for l in input.split('\n')])
Ned Batchelder
This doesn't produce the output specified by the question.>>> input = 'foo\n\n\n\n\nbar\nbaz'>>> output = ''.join([("<p>%s</p>" % l) for l in input.split('\n')])>>> output'<p>foo</p><p></p><p></p><p></p><p></p><p>bar</p><p>baz</p>'
Jason R. Coombs
+1  A: 
def tohtml(manylinesstr):
    return ''.join("<p>%s</p>" % line
          for line in manylinesstr.splitlines()
          if line)

So for example,

print repr(tohtml('foo\n\n\n\n\nbar\nbaz'))

emits:

'<p>foo</p><p>bar</p><p>baz</p>'

as required.

Alex Martelli
+1  A: 

I know you said TG1 my solution is TG2 but can be backported or simply depend on webhelpers but IMO all other implementations are flawed.

Take a look at the converters module both nl2br and format_paragraphs.

Jorge Vargas
I tried using the converters module, but neither function does what the question asks.>>> from webhelpers.html import converters>>> converters.format_paragraphs('foo\n\n\n\n\nbar\nbaz')u'<p>foo</p>\n\n<p>bar\nbaz</p>'>>> converters.nl2br('foo\n\n\n\n\nbar\nbaz')literal(u'foo<br />\n<br />\n<br />\n<br />\n<br />\nbar<br />\nbaz')
Jason R. Coombs
The original question is flawed. format_paragraph does the right thing. As one enter in html doesn't means a new paragraph. That said patches and improvements are welcome, the code is really trivial.
Jorge Vargas