python/genshi newline to html <p> paragraphs

时光怂恿深爱的人放手 提交于 2019-12-07 17:38:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!