Search code examples
pythondjangotemplatesdjango-templatestemplatetags

Override existing Django Template Tags


Is it possible to override an existing Django Template Tag? or is it necessary to customize the template file and create a new Template Tag?


Solution

  • Yes.

    As django is basically a python library (as with everything in python) you can over-write anything you'd like.

    It's not clear exactly what you'd like to do but it really is pretty easy to roll-your-own templatetag, the docs are pretty clear: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

    This is crazy basic but this is the kind of template I use to start building a custom template tag from:

    myapp/templatetags/my_custom_tags.py (must have __init__.py in this directory)

    from django import template
    register = template.Library()
    
    class CustomTag(template.Node):
        def render(self, context):
            context['my_custom_tag_context'] = "this is my custom tag, yeah"
            return ''
    
    @register.tag(name='get_custom_tag')
    def get_custom_tag(parser, token):
        return CustomTag()
    

    Usage in your template goes like this:

    {% load my_custom_tags %}
    {% get_custom_tag %}
    {{my_custom_tag_context}}
    

    You probably want to parse the token, and you probably want some kind of __init__ in the class, but it does go to show how basic it is.


    You can browse through the existing 'default' templatetags, replicate and modify them to your heart's content.

    There really is some great stuff there: https://github.com/django/django/blob/master/django/template/defaulttags.py