Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django Templating - More Than Just Blocks

Django Templating - More Than Just Blocks

Talk at PyCon 2011

Christine Cheung

March 10, 2012
Tweet

More Decks by Christine Cheung

Other Decks in Programming

Transcript

  1. Django Templating @ PyCon 2012 by Christine Cheung About the

    Presenter Front End Developer President of PyLadies Python Diversity Organization Speaker at DjangoCon 2011 Best Practices for Front End Django Developers
  2. Django Templating @ PyCon 2012 by Christine Cheung What I’m

    Going to Talk About Intro to Templating Effective Use of Built-In Tags Extending Templates Template Loading What’s New
  3. Django Templating @ PyCon 2012 by Christine Cheung Django Templating

    101 This is the End User Experience Balance between power and ease Design
  4. Django Templating @ PyCon 2012 by Christine Cheung Helpful Tools

    Django template theme for your IDE syntax highlighting, autocompletion django-debug-toolbar template paths, session variables Print out tag/filter reference guide
  5. Django Templating @ PyCon 2012 by Christine Cheung Folder and

    File Structure Keep templates in one place
  6. Django Templating @ PyCon 2012 by Christine Cheung Style Guide

    Think PEP 8 coding conventions consistent spacing {% load %} all template tags up top try {# comment #} rather than <!-- this --> also, {% comment %} {% endcomment %}
  7. Django Templating @ PyCon 2012 by Christine Cheung The Basics

    Start with base.html template <!doctype html> <head> <title>{% block title %}demo{% endblock title %}</title> </head> <body> {% block content %}{% endblock content %} </body> </html>
  8. Django Templating @ PyCon 2012 by Christine Cheung The Basics

    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 %}
  9. Django Templating @ PyCon 2012 by Christine Cheung Common Blocks

    I use these in practically every project: title meta_tags, robots extra_head content extra_js
  10. Django Templating @ PyCon 2012 by Christine Cheung Block Practices

    End your block structures {% block title %} foo { % endblock title %} instead of {% block title %} foo {% endblock %} Can’t repeat blocks however: context processor, include, custom template tag Don’t “over block”
  11. Django Templating @ PyCon 2012 by Christine Cheung Including Templates

    {% include “snippet.html” %} great for repeating template segments I heard you liked includes... don’t include an include in an include
  12. Django Templating @ PyCon 2012 by Christine Cheung Variables Tend

    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
  13. Django Templating @ PyCon 2012 by Christine Cheung Security By

    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! ***
  14. Django Templating @ PyCon 2012 by Christine Cheung URLs Name

    {% 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”
  15. Django Templating @ PyCon 2012 by Christine Cheung Forms For

    heavy form action, take a look at: django-floppyforms (HTML5) django-crispy-forms {% include form.html %} as_ul makes more sense than p or table
  16. Django Templating @ PyCon 2012 by Christine Cheung ... to

    pick a box There are multiple ways to accomplish the same task No ultimately right or wrong way use what suits you or your team
  17. Django Templating @ PyCon 2012 by Christine Cheung An Example

    {% if foo.bar %} {{ foo.bar }} {% else %} {{ foo.baz }} {% endif %} or... {% firstof foo.bar foo.baz %}
  18. Django Templating @ PyCon 2012 by Christine Cheung Custom Tags

    and Filters demo/ models.py templatetags/ __init__.py demo_utils.py views.py {% load demo_utils %}
  19. Django Templating @ PyCon 2012 by Christine Cheung Making a

    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" }}
  20. Django Templating @ PyCon 2012 by Christine Cheung Making a

    Custom Tag Tags are a bit more complex two steps: compiling and rendering Decide its purpose but start simple
  21. Django Templating @ PyCon 2012 by Christine Cheung A Simple

    Example <p> It is now {% current_time "%Y-%m-%d %I:%M %p" %} </p>
  22. Django Templating @ PyCon 2012 by Christine Cheung Simple Tag

    from django import template register = template.Library() @register.simple_tag def current_time(format_string): try: return datetime.datetime.now().strftime(str(format_string)) except UnicodeEncodeError: return 'oh noes current time borked'
  23. Django Templating @ PyCon 2012 by Christine Cheung Nodes and

    Stuff import datetime from django import template register = template.Library() @register.tag(name="current_time") def do_current_time(parser, token): try: tag_name, format_string = token.split_contents() except ValueError: msg = '%r tag requires a single argument' % token.split_contents()[0] raise template.TemplateSyntaxError(msg) class CurrentTimeNode(template.Node): def __init__(self, format_string): self.format_string = str(format_string) def render(self, context): now = datetime.datetime.now() return now.strftime(self.format_string)
  24. Django Templating @ PyCon 2012 by Christine Cheung Easier Template

    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
  25. Django Templating @ PyCon 2012 by Christine Cheung DO NOT!!!

    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
  26. Django Templating @ PyCon 2012 by Christine Cheung Template Loading

    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)
  27. Django Templating @ PyCon 2012 by Christine Cheung Replacing the

    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.
  28. Django Templating @ PyCon 2012 by Christine Cheung Jinja2 and

    Django and You Pros functions callable from templates loop controls multiple filter arguments slight performance increase
  29. Django Templating @ PyCon 2012 by Christine Cheung Jinja2 and

    Django and You Cons more dependencies and overhead extra time spent on development and support too much logic in templates minimal speed increase
  30. Django Templating @ PyCon 2012 by Christine Cheung Speeding Up

    Templates Cache Template Loader django-template-preprocessor compiles template files django-pancake flatten template files but also remember other bottlenecks...
  31. Django Templating @ PyCon 2012 by Christine Cheung New in

    Django 1.4 Custom Project and App templates startapp / startproject -- template combine with your favorite boilerplate Else if {% elif %}