How to use jinja2 as a templating engine in Django 1.8
NickName:biiiju Ask DateTime:2015-06-08T13:13:57

How to use jinja2 as a templating engine in Django 1.8

I have been looking on how to use jinja2 in django 1.8, but there is no complete source for using django with jinja2. I was wondering if you guys knew the process for using jinja2 in django. I have looked through the the official documentation and I have looked at the following question: How to setup django 1.8 to use jinja2?

but none of them clearly explain how to use jinja2 in an put-togther manner. I just started using django and don't know all the lingo in the docs. I would really appreciate the help.

Copyright Notice:Content Author:「biiiju」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/30701631/how-to-use-jinja2-as-a-templating-engine-in-django-1-8

Answers
MaxBlax360 2021-10-08T16:31:30

Update for Django 3+: Real Life config Jinja2 3.0.X +\n<project_name>/settings.py\nTEMPLATES = [\n{\n "BACKEND": "django.template.backends.jinja2.Jinja2",\n "DIRS": [os.path.join(BASE_DIR, "ui", "templates")], # You can add a subdirectory like /jinja2 if you don't want Jinja2 to be default. But for consistency I do not recommand\n "APP_DIRS": True,\n "OPTIONS": {\n 'environment': ".".join([os.path.basename(BASE_DIR), 'jinja2.environment']),\n "context_processors": [\n "django.contrib.auth.context_processors.auth",\n "django.template.context_processors.debug",\n "django.template.context_processors.i18n",\n "django.template.context_processors.media",\n "django.template.context_processors.static",\n "django.template.context_processors.tz",\n "django.contrib.messages.context_processors.messages",\n ],\n }\n},\n{\n "BACKEND": "django.template.backends.django.DjangoTemplates",\n "DIRS": [],\n "APP_DIRS": True,\n "OPTIONS": {\n "context_processors": [\n "django.template.context_processors.debug",\n "django.template.context_processors.request",\n "django.contrib.auth.context_processors.auth",\n "django.contrib.messages.context_processors.messages",\n ],\n },\n},]\n\n<project_name>/<project_name>/jinja2.py\nimport inspect\nimport logging\n\nfrom django.contrib import messages\nfrom jinja2 import Environment, pass_context\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom django.urls import reverse\n\nimport ui.templatetags.extras as extras_filters\nfrom crispy_forms.utils import render_crispy_form\n\nlogger = logging.getLogger(__name__)\n\n# /!\\ This this how you make csrf token generated by crispy properly injected\n@pass_context \ndef crispy(context, form):\n return render_crispy_form(form, context=context)\n\ndef environment(**options):\n logger.debug("Jinja2 environment loading")\n env = Environment(**options)\n env.globals.update({\n "get_messages": messages.get_messages,\n "static": staticfiles_storage.url,\n "crispy": crispy, # this line is different\n "url": reverse,\n })\n # Bonus, get your django custom templatetag, backward compatible with Django Template\n env.filters.update(dict(inspect.getmembers(extras_filters, inspect.isfunction)))\n return env\n\n/ui/views.py\nimport logging\n\nfrom django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit\n\n\nlogger = logging.getLogger(__name__)\n\nclass AddRemoteServerForm(forms.Form):\n name = forms.CharField(max_length=20, min_length=3)\n url = forms.CharField(max_length=200)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n 'name',\n 'url',\n Submit('submit', 'Associate Server')\n )\n\n<project_name>/ui/views.py\ndef add_remote_server(request):\nif request.method == 'POST':\n form = AddRemoteServerForm(request.POST)\n logger.debug(form.data.dict())\n logger.debug("Form valid ? %s " % form.is_valid())\n if form.is_valid():\n d = form.data.dict()\n # TODO: Implmenent your business logic\n return redirect('/remote_servers/')\nelse:\n form = AddRemoteServerForm()\ncontext = {'form': form}\nreturn render(request, 'form.html', context)\n\n<project_name>/ui/templates/form.html\n{% extends "base.html" %}\n{% block extraappendjavascript %}\n{% endblock %}\n{% block content %}\n<div class="container">\n <div class="card">\n <div class="card-body">\n {{ crispy(form) }}\n </div>\n\n </div>\n</div>\n{% endblock %}\n\n<project_name>/ui/templatetags/extras.py # Bonus, FYI\nimport logging\nimport os\nfrom datetime import datetime, timedelta\n\nfrom django.utils.safestring import mark_safe\nfrom django.template import Library\n\nimport json\n\n\nregister = Library()\n\nlogger = logging.getLogger(__name__)\[email protected](is_safe=True)\ndef js(obj):\n try:\n return mark_safe(json.dumps(obj))\n except Exception:\n return "{}"\n",


doru 2015-06-08T17:29:58

Frist you have to install jinja2:\n\n$ pip install Jinja2\n\n\nThen modify your TEMPLATES list in the settings.py to contain the jinja2 BACKEND :\n\nTEMPLATES = [\n\n {\n 'BACKEND': 'django.template.backends.jinja2.Jinja2',\n 'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')],\n 'APP_DIRS': True,\n 'OPTIONS': {'environment': 'myproject.jinja2.Environment',}, \n },\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\n\nwhere templates/jinja2 is the directory with your jinja2 template files.\n\nAnd in your views.py file:\n\nfrom __future__ import absolute_import # Python 2 only\nfrom jinja2 import Environment\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom django.urls import reverse\n\ndef environment(**options):\n env = Environment(**options)\n env.globals.update({\n 'static': staticfiles_storage.url,\n 'url': reverse,\n })\n return env\n\n\nThis makes static and url available in your Jinja2 templates.\n\nP.S. For more details see this article.",


IvanX 2016-12-22T12:45:18

Took me quite some time to figure out everything, answers here weren't all that helpful.\n\ndoru's answer is closest to truth but is incomplete.\n\nHow to use jinja as templating language:\n\n1.Create jinja2.py file in your project folder. This is required to modify the default jinja2 Environment (in our case, passing some additional global variables).\n\nlocation: {root}/main/jinja2.py:\n\nfrom __future__ import absolute_import # Python 2 only\nfrom jinja2 import Environment\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom django.core.urlresolvers import reverse\n\ndef environment(**options):\n env = Environment(**options)\n env.globals.update({\n 'static': staticfiles_storage.url,\n 'url': reverse,\n })\n return env\n\n\n2.Add jinja2 backend to django project settings file, including our modified environment.\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.jinja2.Jinja2',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'environment': \"main.jinja2.environment\",\n },\n },\n ...\n]\n\n\n3.Now you no longer need to import jinja2 anywhere, in your views, you will be using jinja templates through django just like django templates:\n\nfrom django.shortcuts import render\n\ndef index(request, **kwargs):\n return render(request, \"index.html.j2\", {'title': 'MyTitle', 'text': \"MyText\"})\n\n\nAnd finally, with APP_DIRS set to True jinja will search templates in all installed apps jinja2 directories. (unlike DTL that searches for templates folder). If you want to change that behavior, or want some extra tweaking, like extension match, filtering or global variables, you should look at django-jinja extension.\n\nYou may also provide additional directories to search for templates via TEMPLATES['DIRS'] option of settings.",


Kostyantyn 2015-08-17T14:16:46

Mixed Django and Jinja2 Template: Environment: Django 1.8 + Jinja2.\n\nI have some legacy Django templates and it's not so easy to rewrite them all at once to Jinja2, so add this custom {% jinja_include \"some_template.jinja\" %} tag to my_custom_tags.py:\n\nfrom django.template.loader import get_template\nfrom django import template\nregister = template.Library()\n\[email protected]_tag(takes_context=True)\ndef jinja_include(context, filename):\n template = get_template(filename)\n return template.render(context.flatten())\n\n\nCall it like this from your Django template:\n\n{% load my_custom_tags %}\n{% jinja_include \"some_template.jinja\" %}\n",


More about “How to use jinja2 as a templating engine in Django 1.8” related questions

How to use jinja2 as a templating engine in Django 1.8

I have been looking on how to use jinja2 in django 1.8, but there is no complete source for using django with jinja2. I was wondering if you guys knew the process for using jinja2 in django. I have

Show Detail

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.con...

Show Detail

Django 1.8 not using Jinja2 template engine

I have followed the instructions on using jinja2 with django1.8. ---> #settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [

Show Detail

Django messages framework with built-in Jinja2 backend

How can I use the Django messages framework with Jinja2 and the built-in Jinja2 backend in Django 1.8? I tried doing it as before, but then remembered that the Jinja2 backend doesn't have the cont...

Show Detail

Using Jinja2 with Django, load tag does not work

I'm building a Django app and chose to use Jinja2 for my templating engine. I noticed after I switched from Django's built in templating engine to Jinja2 the load keyword would not work, ex: {% load

Show Detail

Using django-paging extension with Django and Jinja2/Coffin

Recently I switched my templating engine from default to Jinja2/Coffin. Everything works just fine but I'm having troubles trying to use Django/Jinja2 django-paging (http://linux.softpedia.com/get/

Show Detail

Django 1.8 with Jinja2: Contrib app Admin not working

I upgraded to a fresh install of Django 1.8 and began using Jinja2 as it said that it was supported now and Jinja2 has some features I could use in my project. After finishing adapting the templat...

Show Detail

When to use a Templating Engine in Python?

As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools. But I am ...

Show Detail

Parameterized reusable blocks with Jinja2 (Flask) templating engine

In Jinja2 templating engine (using Flask), I want to achieve something like that: {% reusable_block avatar(user) %} &lt;img src='{{ user.avatar }}' title='{{ user.name }}'/&gt; {% reusable_b...

Show Detail

Using Polymer with App Engine Python Jinja2 Templating, passing Datastore values to polymer elements

I have a question regarding how to handle datastore data coming from a Google App Engine python project with Jinja2 templating for use in a custom Polymer element. I am using the simple getting st...

Show Detail