halmocka
halmocka

Reputation:

python/genshi newline to html <p> paragraphs

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.

Upvotes: 3

Views: 892

Answers (3)

Jorge Vargas
Jorge Vargas

Reputation: 6932

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.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882171

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.

Upvotes: 3

Ned Batchelder
Ned Batchelder

Reputation: 375774

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')])

Upvotes: 2

Related Questions