Search code examples
pythondjangotemplatesdjango-templatestemplatetags

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


{% 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.


Solution

  • 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.