Customization: Custom tags

  1. Extra filters and tags
  2. Customization
  3. Custom filters

http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

You can make your own tags as well. You need a folder to put them in. Create a “templatetags” folder inside of your “postings” folder. It must be a Python package; this means it must have a file called “__init__.py” inside it. The file can be empty, but it must be there:

cd postings

mkdir templatetags

touch templatetags/__init__.py

You can create as many .py files in the templatetags folder as you want. If you want to load the tags (or filters) from a particular file into a template, use “{% load filename %}”, without the “.py”. For example, if you have a “media.py” file with tags and filters, you can load them with “{% load media %}”.

Let’s say we want to be able to include Youtube videos throughout our pages. Youtube has complex code for embedding videos; we can make a template snippet just for embedding Youtube videos, and make a tag that renders that code.

{% embed "6ugx0Z0239Y" %}

{% embed "TO68zwTXFWk" "wide" %}

Create a media.py file with:

from django import template

register = template.Library()

@register.simple_tag

def embed(videoCode, aspect="standard"):

if aspect == 'wide':

width = 560

height = 340

else:

width = 425

height = 344

context = {'videocode': videoCode, 'width': width, 'height': height}

return template.loader.render_to_string('parts/youtube.html', context)

Add “{% load media %}” to the top of index.html. Then, add a “Video of the day” section to the top of the content div:

<div id="content">

<h2>Video of the day!</h2>

{% embed "6ugx0Z0239Y" %}

</div>

You should see a clip from the L’il Abner musical at the top of the index page and the topics page. Replace the embed tag with:

{% embed "TO68zwTXFWk" "wide" %}

And you should see a widescreen clip from Ferris Bueller’s Day Off instead.

You can also use model properties and methods in tags. If you had a slugfield for Youtube videos on each post, called “video”, you could use this to display it:

{% embed post.video %}

Django will pull the Youtube code string out of post.video and send that to the “embed” tag.

You don’t need to add your custom templatetags files to settings.py: Django automatically looks into each app folder, and makes the files in that app’s templatetags folder available to any app. Django knows that “embed” is a tag because of the “@register.simple_tag” decorator above the function. Decorators are a feature of Python that adds common functionality to functions. Anything with an @ symbol above a function definition “decorates” that function.

  1. Extra filters and tags
  2. Customization
  3. Custom filters