Jinja keep indentation on include or macro

jinja2, templates

Solution

One way is to wrap the include in a macro, then because the macro is a function, its output can be passed through the indent filter:

class MyClass:
    def someOp():
        pass

    {% macro someop() %}{% include "someOp.html" %}{% endmacro %}
    {{ someop()|indent }}

By default 'indent' indents 4 spaces and does not indent the first line, you can use e.g. 'indent(8)' to indent further, see http://jinja.pocoo.org/docs/templates/#list-of-builtin-filters for more details.

If what you're including is defined as a macro to begin with then the further wrapper macro is not needed, and you can jump straight to using the indent filter.

Problem

I am wondering if there is any way to keep the indentation with jinja when adding a include or macro inside a file. I would like to use jinja to generating a code file. An example would be File: class.html ``` class MyClass: def someOp(): pass {% include "someOp.html" %} ``` File: someOp.html ``` def someOp2(): pass ``` The result of the template should be: ``` class MyClass: def someOp(): pass def someOp2(): pass ``` If there any way to make jinja prepend the indent before the include tag for each line in the included file? Or is there any way to customize jinja to do this?

Original source

Related problems