Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to register a single template tag for multiple templates?

Tags:

python

django

Is it possible to register a @register.inclusion_tag for multiple templates?

for example:

@register.inclusion_tag('blog/components/tags_list.html',
                        takes_context=True)
def tags_list(context):
    tags = Tag.objects.all()
    return {
        'request': context['request'],
        'blog_page': context['blog_page'],
        'tags': tags
    }

I would like for tags_list to also be available for other templates?

Yes I can just copy and paste the def tags_list(), edit the name and add the corresponding template via another @register, but that's not what I'm looking for.

like image 450
andres Avatar asked Oct 23 '25 04:10

andres


2 Answers

I think you should be able to register the same function with multiple inclusion tags. Based off my reading of https://github.com/django/django/blob/main/django/template/library.py#L136 you should be able to just pass the same function through multiple decorators. You will want to name the tags differently to use different templates.

@register.inclusion_tag('blog/components/tags_list_a.html',
                        name='a', takes_context=True)
@register.inclusion_tag('blog/components/tags_list_b.html',
                        name='b', takes_context=True)
def tags_list(context):
    tags = Tag.objects.all()
    return {
        'request': context['request'],
        'blog_page': context['blog_page'],
        'tags': tags
    }
like image 136
Jacinator Avatar answered Oct 25 '25 19:10

Jacinator


You can register it to work for all templates by registering a simple_tag [Django-doc], not an inclusion_tag:

@register.simple_tag(takes_context=True)
def tags_list(context):
    tags = Tag.objects.all()
    return {
        'request': context['request'],
        'blog_page': context['blog_page'],
        'tags': tags
    }

Now the context will be available in all templates. Since querysets are lazy, it will not make a query unless you iterate over it, or calculate the length for example.

Based on how you implement your template tag, it might make more sense to implement a context processor [Django-doc] instead of a template tag.

like image 32
Willem Van Onsem Avatar answered Oct 25 '25 18:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!