Django template templates of the same name

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 both templatetags into the template

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

      

I have two tags named custom_tag

. How can I use them in my template? Should I rename them?

+3


source to share


1 answer


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

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

This parameter must specify a different name for 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

      

Normally, if you register a tag without a name, Django will use the function as the filter name, but if you pass the arg name when registering the filter, Django will use that as the templatetag name.

Django: Custom Template Tag

If you give them different names when registering a tag, this will be the name you will use to load the tags



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

      

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

Import a tag with a different name

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

If you want to import a tag into your project, you must add your tag, for example:

your_app/template_tags/my_custom_tag

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

from app2.template_tags.app2_tags import custom_tag

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

      

After that, you imported the custom_tag tag into the project with a new name new_custom_tag_name

+1


source







All Articles