Fork me on GitHub

Jan 29, 2009

Writing Template Tags in Django

Template tags are very useful, if you like your Django template language to use your customized syntax.

To write a template tag you need to do a couple things:

Make a Python package named "templatetags" inside your app:

| |~events/
| | |~templatetags/
| | | |-__init__.py
| | | `-events.py
| | |-__init__.py
| | |-admin.py
| | |-manager.py
| | |-middleware.py
| | |-models.py
| | `-views.py

In your template you need to load your custom template tags too:

{% load events %}

And that's it, your events.py file is loaded into your template, but, you need to write some templatetags.

First, think about your template tag, what is it going to be? a filter? or a block alike? (anymore types?), I'll choose the "block alike" since its harder to implement :).

We are going to be able to do:

{% get_event_metadata event.pk as metadatas %}

That will create a "context" "variable" from a pk... here are my models:

I avoided posting the whole source code, since its not relevant.

Now, lets create our template tags, in our events/templatetags/events.py file:

One thing to notice is that when you call the template tag from the template all the events.py gets is a string, and the only way to get the value from that "string" (or variable in this case, is to get it from the context, using template.Variable and the context var, or context.get("varname").attr.

2 comments:

Jeff said...

Great post, looking forward to playing around with this soon. Thanks!

Igor said...

Thank you for reading my blog :)

disclaimer



Things written in this blog are my personal thoughts or points of view, and do not represent at all the position of my employer.

Code in the website is licensed under The MIT License

Content of this blog is:
Creative Commons License
Licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.