Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping whitespace in jinja2 & flask...why do I still need the minus sign?

Tags:

python

jinja2

In my init.py file I have:

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

I expect in my jinja2 template that whitespace will be trimmed, so that:

<div>
{% if x == 3 %}
<small>{{ x }}</small>
{% endif %}
</div>

will render as:

<div>
<small>3</small>
</div>

Instead, I get extra whitespace:

<div>

<small>3</small>

</div>

Why doesn't trim_blocks and lstrip_blocks trim the whitespace?

like image 665
user_78361084 Avatar asked Apr 20 '14 19:04

user_78361084


People also ask

How use Jinja safe filter?

The safe filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled. The documentation on this filter is here. See the section on manual escaping to see which characters qualify for escaping.

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.


1 Answers

It seems like your environment settings are not set before jinja2 loads your template.

class jinja2.Environment([options])

... Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

http://jinja.pocoo.org/docs/dev/api/#jinja2.Environment

Check the order/structure of your code to see how the environment settings vs templates are loaded.

As an aside, jinja2's whitespace control does work as expected without the complexity of environments and loading:

import jinja2

template_string = '''<div>
{% if x == 3 %}
<small>{{ x }}</small>
{% endif %}
</div>
'''
# create templates
template1 = jinja2.Template(template_string)
template2 = jinja2.Template(template_string, trim_blocks=True)

# render with and without settings
print template1.render(x=3)
print '\n<!-- {} -->\n'.format('-' * 32)
print template2.render(x=3)

<div>

<small>3</small>

</div>

<!-- -------------------------------- -->

<div>
<small>3</small>
</div>

I've not used jinja2, but after scanning the docs, loading order seems to be suspect.

like image 80
tmthydvnprt Avatar answered Oct 11 '22 21:10

tmthydvnprt