Jinja2 correctly indent included block

前端 未结 3 1645
深忆病人
深忆病人 2021-02-02 07:35

I have two files:

base.html



    
       
       

        
相关标签:
3条回答
  • 2021-02-02 07:42

    Good question. I believe Jinja2 does not do this.

    The main question you need to ask yourself is why you want the HTML to be correctly indented, since browsers do not care. In a production application it is more efficient to go the other way and strip all the white space to make the page smaller.

    If you are interested in doing this during development then you can pass the HTML generated by render_template() through an indenter such as prettify() from BeautifulSoup. I do not recommend this for a production system, since your functions will take longer to run.

    0 讨论(0)
  • 2021-02-02 07:53

    I know, the question is rather old but I found a nice solution to this problem. You can apply filters to whole text blocks: Template Designer Documentation / Filters

    {% filter indent(width=4) %}
    {% include "./sub-template.yml.j2" %}
    {% endfilter %}
    
    0 讨论(0)
  • 2021-02-02 07:57

    Although I think the increase in document size is a good argument against "correctly" indenting documents, jinja2 actually provides a function to do just what you what:

    indent(s, width=4, indentfirst=False)
    

    which you would use in your base.html with a macro, as described in this answer on SO.

    I would probably make that a macro anyway and call it render_register_form:

    {% macro render_register_form(form) %}
        <h1>Register</h1>
        <form action="" method="post" name="register">
            {{ form.hidden_tag() }}
            {{ form.login.label }} {{ form.login(size=20) }}
            {{ form.password.label }} {{ form.password(size=20) }}
            <input type="submit" value="Register">
        </form>
    {% endmacro %}
    

    and then include it where needed, for example, with 8 spaces indentation, as:

    {{ render_register_form(my_form)|indent(8, True) }}
    
    0 讨论(0)
提交回复
热议问题