How come my template tag doesn't work in Django Templates?

3.5k views Asked by At
{% gen_aws "hello" %}

In my file, I do this:

# I want to add "goodbye" to every word passed to this tag.
@register.tag(name="gen_aws")
def gen_aws(s):
    return s + "goodbye"

The .py file is fine...I'm including everything fine. I have other template filters in there that work fine. But then I added this in that file, and this template tag doesn't work.

3

There are 3 answers

3
AndiDog On BEST ANSWER

Your description of "doesn't work" is not very accurate (to be exact it doesn't exist). But I guess you get an error because the tag is not found.

The documentation clearly states that you need a "templatetags" module in your app, with a submodule like "mytags", for example. Then you have to include these tags in each template you want to use them. You can do that with {% load mytags %}.

The "mytags" module then contains your "gen_aws" tag.

EDIT: The error "gen_aws() takes exactly 1 argument (2 given)" occurs because normal tags can parse their parameter in a very customized way. Therefore they get the arguments "parser" and "token". In your case, a so-called simple tag should be enough - Django then automatically parses parameters for you and passes them as Python values. So just replace @register.tag by @register.simple_tag.

0
Super Kai - Kazuya Ito On

You need to use @register.simple_tag as shown below instead of @register.tag whose function cannot get the values but can get the tokens from the template tag and you can see my answer explaining more about @register.simple_tag and @register.tag:

# @register.tag(name="gen_aws")
@register.simple_tag(name="gen_aws")
def gen_aws(s):
    return s + "goodbye"
0
kqr On

Another possible cause of the "no attribute 'must_be_first'" error is that you've forgot to inherit from django.template.Node in your class. (Since this is pretty much the only Google result for that phrase I thought I'd add this here to save a couple of minutes for the next person.)