问题
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.
回答1:
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.
回答2:
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')])
回答3:
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.
来源:https://stackoverflow.com/questions/1257746/python-genshi-newline-to-html-p-paragraphs