python/genshi 换行符到 html

;段落

发布于 2024-08-02 07:36:46 字数 250 浏览 4 评论 0原文

我试图用 genshi 输出评论的内容,但我不知道如何将换行符转换为 HTML 段落。

下面是一个测试用例:

输入:'foo\n\n\n\n\nbar\nbaz'

输出:

foo

< ;p>bar

baz

我到处都在寻找这个函数。我在 genshi 或 python 的 std lib 中找不到它。我用的是TG 1.0。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘦怹 2024-08-09 07:36:46
def tohtml(manylinesstr):
    return ''.join("<p>%s</p>" % line
          for line in manylinesstr.splitlines()
          if line)

例如,

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

发出:

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

根据需要

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.

深海夜未眠 2024-08-09 07:36:46

Genshi 中可能有内置函数,但如果没有,这将为您完成:

output = ''.join([("<p>%s</p>" % l) for l in input.split('\n')])

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')])
热血少△年 2024-08-09 07:36:46

我知道你说 TG1,我的解决方案是 TG2,但可以向后移植或简单地依赖于 webhelpers,但 IMO 所有其他实现都有缺陷。

查看转换器模块 nl2br 和格式段落。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文