Lorena Nicole
Lorena Nicole

Reputation: 519

Jinja2 templating not working in in Django 1.9

Per the instructions on the Django 1.9 tutorial I've added another file in the project root with the Environment settings -

from __future__ import absolute_import  # Python 2 only

from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse

from jinja2 import Environment


def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
    })
    return env`

(Granted to load the proper jinja2 I had to rename the file something differently, in this case jinja2env.py in project root)

And I updated settings.py with the new templating backend:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(PROJECT_ROOT, 'templates').replace('\\','/')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
{
    'BACKEND': "django.template.backends.jinja2.Jinja2",
    'DIRS': [os.path.join(PROJECT_PATH, 'campaigns/templates').replace('\\','/')],
    "APP_DIRS": True,
    "OPTIONS": {
        'environment': 'jinja2env.Environment',
    }
},

In the view I'm working on I use the using parameter to specify the jinja2 templating engine:

return render(request, 'jinja2/index.html', context={'projects': projects, 'counter': 0}, status=200, using='jinja2')

Yet when the template goes to render I have following error: 'static' is undefined. Clearly my setup is wrong or I am not doing something correct. The template starts as such:

<link rel="stylesheet" type="text/css" href="{{ static('stylesheets/main.css') }}">

What am I doing wrong? I don't use {% load static %} since it isn't a Django template ... so I'm at a loss.

Upvotes: 2

Views: 3135

Answers (2)

Derek Kwok
Derek Kwok

Reputation: 13078

You're loading the wrong environment. In your code jinja2env.Environment actually refers to default Environment from jinja2.Environment.

"OPTIONS": {
    'environment': 'jinja2env.Environment',
}

should be changed to

"OPTIONS": {
    'environment': 'jinja2env.environment',
}

Notice the lowercase environment, which is the environment you defined inside jinja2env.py.

Upvotes: 5

kungphu
kungphu

Reputation: 4869

Based on your settings and the accepted answer to this question, it appears you should try adding the static context processor.

Upvotes: 0

Related Questions