Skip to content

indent filter ignores blank=False when first=True on first line #2176

Description

@abstract-official

Currently, indent filter indents the first line no matter whether it's empty if first is True, even if blank is False (which is the default).

from jinja2 import Environment
Environment().from_string("{% filter indent(4, first=True) %}{% endfilter %}").render()

Expected result is "", but actual result is " ".

This is important when rendering something like this (with lstrip_blocks and trim_blocks on):

<head>
  <style>
    /* some default styles, such as: */
    :root {
      color-scheme: light dark;
    }
    {% filter indent(4, first=True) %}
    {% block extra_style %}{% endblock %}
    {% endfilter %}
  </style>
</head>

which becomes:

<head>
  <style>
    /* some default styles, such as: */
    :root {
      color-scheme: light dark;
    }
      </style>
</head>

if extra_style is not overwritten by subtemplates. (There's extra four spaces before </style>.)
However, if subtemplates overwrites this block, then everything is properly indented.

Wrap all styles in a block and let subtemplates use {{ super() }}? Then subtemplates have to care about indentation in base templates, which breaks separation of concerns.

Or compromise with uglily indented things like:

<head>
  <style>
{% filter indent(4, first=True) %}
/* some default styles, such as: */
:root {
  color-scheme: light dark;
}
{% block extra_style %}{% endblock %}
{% endfilter %}
  </style>
</head>

Or, hack with:

<head>
  <style>
    /* some default styles, such as: */
    :root {
      color-scheme: light dark;
    {# Yes, begin the filter before common part ends. More difficulties when editing default styles. #}
    {% filter indent(4) %}
    }
    {% block extra_style %}{% endblock %}
    {% endfilter %}
  </style>
</head>

This is even more significant when rendering e.g. Python or YAML.

Environment:

  • Python version: 3.13.13
  • Jinja version: 3.1.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions