Jinja缩进包含或宏 [英] Jinja keep indentation on include or macro

查看:96
本文介绍了Jinja缩进包含或宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在文件中添加包含或宏时是否有任何方法可以使Jinja缩进.我想使用jinja生成代码文件.一个例子是

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

文件:class.html

File: class.html

class MyClass:
     def someOp():
         pass

     {% include "someOp.html" %}

文件:someOp.html

File: someOp.html

def someOp2():
    pass

模板的结果应为:

class MyClass:
     def someOp():
         pass

     def someOp2():
         pass

对于包含文件中的每一行,是否有任何方法可以使jinja在include标记之前缩进?还是有什么方法可以定制Jinja来做到这一点?

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?

推荐答案

一种方法是将include包裹在宏中,然后由于该宏是函数,因此其输出可以通过缩进过滤器传递:

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 }}

默认情况下,'indent'缩进4个空格并且不缩进第一行,您可以使用例如'indent(8)'以进一步缩进,请参见 http://jinja .pocoo.org/docs/templates/#list-of-builtin-filters 了解更多详细信息.

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.

这篇关于Jinja缩进包含或宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆