gpt4 book ai didi

python - Django 语法高亮导致字符转义问题

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:03 25 4
gpt4 key购买 nike

我一直在致力于我自己的基于 django 的博客(就像我知道的每个人一样)来提高我的 python 能力,我认为添加一些语法突出显示会非常棒。我查看了一些片段,决定组合一些片段并使用 Beautiful Soup 和 Pygments 编写我自己的语法突出显示模板过滤器。它看起来像这样:

from django import template
from BeautifulSoup import BeautifulSoup
import pygments
import pygments.lexers as lexers
import pygments.formatters as formatters

register = template.Library()

@register.filter(name='pygmentize')
def pygmentize(value):
try:
formatter = formatters.HtmlFormatter(style='trac')
tree = BeautifulSoup(value)
for code in tree.findAll('code'):
if not code['class']: code['class'] = 'text'
lexer = lexers.get_lexer_by_name(code['class'])
new_content = pygments.highlight(code.contents[0], lexer, formatter)
new_content += u"<style>%s</style>" % formatter.get_style_defs('.highlight')
code.replaceWith ( "%s\n" % new_content )
content = str(tree)
return content
except KeyError:
return value

它会查找这样的代码块,并突出显示并广告相关样式:

<code class="python">
print "Hello World"
</code>

这一切都工作正常,直到我包含的一段代码中有一些 html。现在,我知道了我需要的所有 html,因此我直接在其中编写我的博客文章,并且在渲染到模板时,只需将帖子正文标记为安全即可:

{{ post.body|pygmentize|safe }}

这种方法会导致代码块中的任何 html 都只呈现为 html(即不显示)。我一直在尝试对过滤器从正文中提取的代码使用 django escape 函数,但我似乎永远无法完全正确。我认为我对转义内容的理解还不够完整。我还尝试在帖子正文中编写转义版本(例如 <),但它只是以文本形式出现。

标记 html 进行显示的最佳方式是什么?我这一切都错了吗?

谢谢。

最佳答案

我终于找到了一些时间来解决这个问题。当 beautiful soup 拉入内容并且其中包含标签时,该标签将被列为列表的子节点。这行是罪魁祸首:

new_content = pygments.highlight(code.contents[0], lexer, formatter)

[0] 切断了代码的其他部分,它没有被错误解码。我的错误发现能力很差。该行需要替换为:

new_content = pygments.highlight(code.decodeContents(), lexer, formatter)

这里的类(class)是确保您知道问题是什么,并了解您的库如何工作。

关于python - Django 语法高亮导致字符转义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1607979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com