Django template tags with same name

好久不见. 提交于 2019-12-01 06:17:12

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!