views:

42

answers:

2

I’ve written a custom template tag:

def mytag(para):
    return something

In my template I am getting a value {{value}}. Now I am using {{value|mytag}} to apply the tag to the value, and it is throwing a syntax error.

+2  A: 

To use template tags in Django, you wrap the name of the tag in {% and %}, like this:

{% mytag %}

If your tag takes a parameter, as yours seems to, you pass the parameter after the name of the tag:

{% mytag value %}

The syntax you were trying to use — {{ value|mytag }} is for template filters, not tags.

Paul D. Waite
+5  A: 

Your example looks like a filter. If that's all you want, it's fairly simple. Paul's links to the documentation should provide a fairly clear explanation of how and why to do things. Here's a quick start that should get you up and running though.

  1. Create a folder in your app called "templatetags" with an empty _init_.py file
  2. Create a file to hold your custom tags, we'll say "tags.py" for now.

your tags.py file should look something like this:

from django import template
register = template.Library()

@register.filter
def mytag(para):
    return 'something'

then, in your template, you'll first have to load your custom tags, then you can have access to it.

{% load tags %}

My new value is: {{ value|mytag }}
Aaron