I have the template below:
{% macro entry(e) %}
<li>
<a href="{% if 'link' in e %}{{ e.link }}{% else %}{{ e.path }}{% endif %}">
<code>{{ e.title }}</code>
</a>{% if e.desc %} - {{ e.desc }}{% endif %}
{% if e.date %}<time datetime="{{ e.date }}"> ({{ e.date.split('-')[0] }})</time>{% endif %}
</li>
{% endmacro %}
<ul>
{% for e in entries %}
{{ entry(e) }}
{% endfor %}
</ul>
which I'm trying to render into this HTML with proper indentation and no blank lines:
<ul>
<li>
<a href="link">
<code>title</code>
</a> - desc
<time datetime="2020"> (2020)</time>
</li>
</ul>
I've tried various permutations of trim_blocks and lstrip_blocks to no avail. How can I achieve the desired output?
Sample code:
from jinja2 import Environment, FileSystemLoader, Template
foo = (
(True, True),
(True, False),
(False, True),
(False, False),
)
template_string = """
{% macro entry(e) %}
<li>
<a href="{% if 'link' in e %}{{ e.link }}{% endif %}">
<code>{{ e.title }}</code>
</a>{% if e.desc %} - {{ e.desc }}{% endif %}
{% if e.date %}<time datetime="{{ e.date }}"> ({{ e.date.split('-')[0] }})</time>{% endif %}
</li>
{% endmacro %}
<ul>
{% for e in entries %}
{{ entry(e) }}
{% endfor %}
</ul>
"""
entries = [
{'title': 'title', 'date': '2020', 'desc': 'desc', 'link': 'link'}
]
for trim_blocks, lstrip_blocks in foo:
env = Environment(trim_blocks=trim_blocks, lstrip_blocks=lstrip_blocks)
template = env.from_string(template_string)
print("------------------------")
print("trim_blocks:", trim_blocks)
print("lstrip_blocks:", lstrip_blocks)
print("------------------------")
print(template.render(entries=entries))
# ------------------------
# trim_blocks: True
# lstrip_blocks: True
# ------------------------
#
# <ul>
# <li>
# <a href="link">
# <code>title</code>
# </a> - desc<time datetime="2020"> (2020)</time></li>
#
# </ul>
# ------------------------
# trim_blocks: True
# lstrip_blocks: False
# ------------------------
#
# <ul>
# <li>
# <a href="link">
# <code>title</code>
# </a> - desc <time datetime="2020"> (2020)</time></li>
#
# </ul>
# ------------------------
# trim_blocks: False
# lstrip_blocks: True
# ------------------------
#
#
# <ul>
#
#
# <li>
# <a href="link">
# <code>title</code>
# </a> - desc
# <time datetime="2020"> (2020)</time>
# </li>
#
#
# </ul>
# ------------------------
# trim_blocks: False
# lstrip_blocks: False
# ------------------------
#
#
# <ul>
#
#
# <li>
# <a href="link">
# <code>title</code>
# </a> - desc
# <time datetime="2020"> (2020)</time>
# </li>
#
#
# </ul>