Django template tags with same name

2020-03-24 04:05发布

问题:

For example I have 2 templatetags

app1  
    templatetags  
        app1_tags.py  
            def custom_tag()  
app2  
    templatetags  
        app2_tags.py  
            def custom_tag()  

If I load in template both templatetags

{% load app1_tags %}
{% load app2_tags %}

I have two tags with the name custom_tag. How can I use them in my template? Must I rename them?

回答1:

I know this is not the best solution but depending on your needs it can be helpful.

This only works if the apps are made by you or if you overwrite the template tags

This option is to give different names to each tag:

app1_tags.py

@register.filter(name='custom1')
def custom_tag():
    # Your code

app2_tags.py

@register.filter(name='custom2')
def custom_tag():
    # Your code

Usually if you register the tag without telling a name, Django will use the function as filter name, but if you passes the arg 'name' when you are registering the filter, Django will use that as the templatetag name.

Django: Custom Template tag

If you give them different names when you register the tag, that will be the name that you will use to load the tags

{% load custom1 %}
{% load custom2 %}

You only would need to customize the name of one of them, you can use the original name of the other

Import tag under different name

As @Igor suggested, another option is to import the template you want to use with another name, let's say like an alias so you avoid the conflict between different tags/filters with the same name.

Assumming you want to import the tag to your project you should add your tag like:

your_app/template_tags/my_custom_tag

To import the tag from app2 on your app with a different name you just need to add into the file my_custom_tag:

from app2.template_tags.app2_tags import custom_tag

register.filter(name="new_custom_tag_name", custom_tag)

After this you have imported the tag custom_tag to your project with a new name new_custom_tag_name