Reputation: 12824
I have found that Jinja2 templates have the .blocks
property, which provides access to named blocks. However, it doesn't provide comment data (understandably).
Is there a programmatic or reliable way to retrieve comment content from a Jinja2 template? (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:
{#
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?
Upvotes: 2
Views: 1700
Reputation: 7882
I browsed through jinja's source code and other articles, and there does not seem to be a way to collect jinja2 comments natively. 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
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. Using BeautifulSoup does support collecting comments natively with ease
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']
Upvotes: 0