Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to clean up the html that jinja2 produces?

Tags:

python

jinja2

We are using jinja2 to create our html but, because of the many loops and other things we do in jinja to produce the html, the html 'looks' ugly....(note: this is just for aesthetics). Is there anything we can do to clean up the html? (Other than the obvious of cleaning up our jinja2 code, which would make our template somewhat unreadable to us staffers)

Something like beautiful soup's prettify?

(Yes, I realize this question is a pretty nit-picky question...the ocd in me says to clean it up).

for instance:

                              <table>

      <tbody>


                  <tr>
                    <td>

                     a column

                    </td>




                                <td>

                                    a value

                                </td>
                      </tr>
                     </tbody>
           </table>     

Pretty ugly, eeh?

like image 567
kristen Avatar asked Jun 06 '13 00:06

kristen


3 Answers

Add '-' to the tags:

{%- if 'this'=='this' -%}
    {{ blah }}
{%- endif -%}
like image 149
user_78361084 Avatar answered Nov 19 '22 07:11

user_78361084


It looks like someone out there created a library to do just what need. See this library which I found attached to this question (whom you should upvote).

like image 20
sarwar Avatar answered Nov 19 '22 07:11

sarwar


You can also configure Jinja to replace tags with nothing (instead of an empty line) by setting trim_blocks and lstrip_blocks to True. For example, in a Flask app, you might write:

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

The documentation explains whitespace control further.

like image 1
c-x-berger Avatar answered Nov 19 '22 07:11

c-x-berger