3

I am encountering the following error when attempting to use jinja2 templates with django 1.8 "Encountered unknown tag 'with'".

The same template works fine on my flask application but when attempting to use the with functionality of jinja 2 I get that error.

inside of the jinja template

{% with %}
    {% set vartest = 42 %}
    {{ vartest }}
{% endwith %}

inside of my jinja2 environment customization

def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url_for': reverse,
        'STATIC_URL': STATIC_URL
    })
    return env
Moylin
  • 737
  • 1
  • 9
  • 20
  • Do you know which version of `jinja2` you are using? `with` was new in 2.3. – jonrsharpe Jul 22 '15 at 17:13
  • pip show gives me Name: Jinja2 Version: 2.7.3 – Moylin Jul 22 '15 at 17:14
  • 1
    It seems that `with` is [an extension](http://jinja.pocoo.org/docs/dev/extensions/#with-extension), try adding `options.setdefault('extensions', []).append('jinja2.ext.with_')` before you create the `Environment`. – jonrsharpe Jul 22 '15 at 17:17
  • Thank you, that fixed the issue, please submit as an answer and I'll upvote it. – Moylin Jul 22 '15 at 17:31

2 Answers2

5

The with statement was new in version 2.3 of Jinja; if you have something earlier, use pip install --upgrade Jinja2 to get the latest version.

It's also an extension, so you'll have to include it in the Environment, e.g. by adding:

options.setdefault('extensions', []).append('jinja2.ext.with_')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Would you also add a note you can also put in it your settings file where it likely would go for most people i bet. I appreciate your help with this. – Moylin Jul 22 '15 at 17:36
  • @Moylin I don't know the syntax for that; why not add it as a separate answer? – jonrsharpe Jul 22 '15 at 17:37
  • Just curious, was that functionality documented somewhere, i didn't even see where to pass extension configuration anywhere. – Moylin Jul 22 '15 at 17:39
  • Be nice if the Jinja docs referenced this where the with statement is documented...thanks. – Rob Dec 04 '16 at 00:55
1

This can also be configured in your settings file.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'your/django/templates',
        ],
        'APP_DIRS': True,
    },
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [
            'your/jinja2/templates.',
        ],
        'OPTIONS':{
            'environment': 'app.project.jinja2.environment',
            'extensions': ['jinja2.ext.with_']}
    }
]
Moylin
  • 737
  • 1
  • 9
  • 20