Configure Flask for Django 1.8.
Django + Jinja2
View Slide
Django Templates• The Django Template Language• How Django loads templates
Django Templates• The Django Template Language• How Django loads templatesDTL
{% for user in users.all %} {{ user.username|capitalize }} {% endfor %}
{% for user in users.all %} {{ user.username|capitalize }} {% endfor %} (Template) Tag
{% for user in users.all %} {{ user.username|capitalize }} {% endfor %} Variable
{% for user in users.all %} {{ user.username|capitalize }} {% endfor %} Variable + Filter
The DTL• Simple syntax with few rules• Lightweight extensions• Self-contained
But…• Awkward DSL• No scoped functions• Slow with frequent rendering
Django 1.8• django.template• django.template.backends
TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_DEBUG TEMPLATE_STRING_IF_INVALID TEMPLATE_DIRS TEMPLATE_LOADERSThe LanguageThe System
TEMPLATES = [ { 'BACKEND': '...', 'DIRS': [], 'OPTIONS': { 'context_processors': [...], 'debug': False, 'string_if_invalid': '', }, }, ]Language-specific SetupTemplate-loading Setup
Jinja2• Armin Ronacher (aka mitsuhiko)• Inspired by the DTL• Standalone library• More programmer-friendly
{% for user in users.all() %} {{ user.username.toupper() }} {% endfor %} Function calling
{% for user in users.get_friends(me) %} {{ user.username.toupper() }} {% endfor %}
Settings for Jinja2{ 'BACKEND': ( 'django.template.backends.' 'jinja2.Jinja2'), 'DIRS': [], 'APP_DIRS': True, },
demoapp├── jinja2│ └── a_jinja2_template.html├── models.py├── templates│ └── a_django_template.html├── urls.py└── views.py
demoapp├── jinja2│ └── a_jinja2_template.html├── models.py├── templates│ └── a_django_template.html├── urls.py└── views.pyConfigurable (not recommended)
Jinja2 for Django• Auto-escape on• Custom template loader• Debug enhancements• Auto-reload• Undefined raises exceptions
But• Jinja2 is not built (just) for Web• Web-related functionalities• Django internals
{% url 'pages:page' name=page_name %} {% static 'base/css/site.min.css' %} {% trans 'This is my website!' %} {% csrf_token %}
https://github.com/MoritzS/jinja2-django-tags
{ 'BACKEND': ('django.template.backends.' 'jinja2.Jinja2'), 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'extensions': [ 'jdj_tags.extensions.DjangoStatic', 'jdj_tags.extensions.DjangoI18n', ] }, },
Jinja2 vs DTL• Functions vs template tags• Methods vs filters• Extensions are loaded by project
The Flask Way• {% url_for(endpoint, **kwargs) %}• Endpoint 'static'• {% get_flashed_messages(...) %}• I18n API (already pretty similar)• {{ csrf_token() }}
To boldly go where no onehas gone before.