简体   繁体   English

如何从Jinja2模板读取注释块?

[英]How can I read comment blocks from a Jinja2 template?

I have found that Jinja2 templates have the .blocks property, which provides access to named blocks. 我发现Jinja2模板具有.blocks属性,该属性提供对命名块的访问。 However, it doesn't provide comment data (understandably). 但是,它不提供评论数据(可以理解)。

Is there a programmatic or reliable way to retrieve comment content from a Jinja2 template? 是否有编程或可靠的方式从Jinja2模板检索评论内容? (Ideally, I'm avoiding writing a regex, as I presume the parsing is built in... I just haven't found it). (理想情况下,我避免编写正则表达式,因为我假设解析是内置的……我只是没有找到它)。

Here is an example: 这是一个例子:

Given this Jinja2 template: 鉴于此Jinja2模板:

{#
Comment block content.
#}

{% block main %}
This is the main block. We don't really care about it.
{% endblock %}

... I would like to be able to retrieve the following: ...我希望能够检索以下内容:

Comment block content. 注释块内容。


Is there a bulit-in, perhaps undocumented way to get at this content reliably? 是否存在一种可靠的,也许未记录的方式来可靠地获取此内容?

I browsed through jinja's source code and other articles, and there does not seem to be a way to collect jinja2 comments natively. 我浏览了jinja的源代码和其他文章,但似乎没有一种本地收集jinja2注释的方法。 Per Martijin Peter's answer on Jinja2 Inline Comments , the {# #} syntax can be used as inline comments, but they are primarily used for disabling part of the template 根据Martijin Peter对Jinja2内联注释的回答, {# #}语法可以用作内联注释,但主要用于禁用模板的一部分

Answer 回答

{# .. #} is only meant for disabling part of a template {#..#}仅用于禁用模板的一部分

Comment 评论

... Yes, {# ... #} are used for commenting, including commenting out (disabling) part of a template . ...是,{#...#}用于注释,包括注释掉(禁用)模板的一部分

As a work around, you can either use regex (which you've stated you wish to not use) or you can switch to standard HTML comments and use BeautifulSoup . 解决方法是,您可以使用regex(您已声明不希望使用),也可以切换到标准HTML注释并使用BeautifulSoup Using BeautifulSoup does support collecting comments natively with ease 使用BeautifulSoup确实支持轻松地本地收集评论

template = '''<!--
Comment block content.
-->

{% block main %}
This is the main block. We don't really care about it.
{% endblock %}'''

from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(template, 'html.parser')
comments = soup.findAll(text=lambda text: isinstance(text, Comment))
print(comments)

>>>['\nComment block content.\n']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM