Presenter Front End Developer President of PyLadies Python Diversity Organization Speaker at DjangoCon 2011 Best Practices for Front End Django Developers
Django template theme for your IDE syntax highlighting, autocompletion django-debug-toolbar template paths, session variables Print out tag/filter reference guide
Think PEP 8 coding conventions consistent spacing {% load %} all template tags up top try {# comment #} rather than <!-- this --> also, {% comment %} {% endcomment %}
Then have pages inherit from it {% extends “base.html” %} {% block title %}the foo page{% endblock title %} {% block content %} <div id=”foo”> this is a bar. </div> {% endblock content %}
to be objects passed from a view Modify objects with filters {{ variable|lower }} Loop through them using tags {% if variable %} foo {% else %} bar {% endif %} You can also create your own filters and tags
default, Django’s security is rather solid on the template side of things... but if you use safe or {% autoescape %} *** make sure you sanitize the data! ***
{% url %} tags as much as possible define URL Pattern in urls.py url(r'^foo/$', foo, name="foo"), <a href=”{% url “foo” %}”>foo</a> ”{{ STATIC_URL }}css/style.css” NOT “/static/css/style.css”
Custom Filter @register.filter(name='remove') from django import template register = template.Library() @register.filter def lower(value): # lowercased value with no passed arguments return value.lower() {{ foo|lower }} if you always expect a string as first argument, use @stringfilter def cut(value, argument): # remove passed arguments from value return value.replace(argument, '') {{ foo|remove:"bar" }}
Tag Creation django-templatetag-sugar makes it simple to define syntax for a tag django-classy-tags class based template tags extensible argument parse for less boilerplate
Do not write a template tag that runs logic or at worst, even run Python from a custom tag it defeats the purpose of a templating language dangerous difficult to support
Logic Use Cases TEMPLATE_LOADERS setting from django.conf import settings from django.template import TemplateDoesNotExist def load_template_source(template_name, template_dirs=None): for filepath in get_template_sources(template_name, template_dirs): try: # load in some templates yo except IOError: pass raise TemplateDoesNotExist(template_name)
Templating Engine You can replace the built in templating engine Jinja2, Mako, Cheetah, etc But why? More familiar with another template language Performance Boost Different logic control and handling Risk “frankensteining” your project.