具有相同名称的Django模板标签 [英] Django template tags with same name
问题描述
例如我有2个模板标签
app1
templatetags
app1_tags.py
def custom_tag()
app2
templatetags
app2_tags.py
def custom_tag()
如果我加载模板两个模板标签
{%load app1_tags%}
{ %load app2_tags%}
我有两个名称为 custom_tag
。我如何在我的模板中使用它们?我必须重命名他们吗?
我知道这不是最好的解决方案,但根据您的需要,这可能是有帮助的。
只有应用程序是由您制作的,或者您覆盖模板标签
此选项是为每个标签提供不同的名称:
app1_tags.py
@ register.filter(name ='custom1')
def custom_tag():
#您的代码
app2_tags.py
@register。过滤器(name ='custom2')
def custom_tag():
#您的代码
通常,如果您不注明名称,Django将使用该函数作为过滤器名称,但是如果您在注册过滤器时传递了arg'name',那么Django将会使用它作为模板名称。 p>
如果您在注册t时给他们不同的名称ag,这将是您将用于加载标签的名称
{%load custom1%}
{ %load custom2%}
您只需要自定义其中一个的名称,即可使用其他的原始名称
导入不同名称下的标签
由于@Igor建议,另一个选项是使用另一个名称导入您要使用的模板,就像一个别名,以避免使用相同名称的不同标签/过滤器之间的冲突。
your_app / template_tags / my_custom_tag
要使用不同的名称从应用程序的app2导入标签,只需添加到 my_custom_tag
from app2.template_tags.app2_tags import custom_tag
register.filter(name =new_custom_ tag_name,custom_tag)
此后,您将标签 custom_tag 导入到您的项目使用新名称 new_custom_tag_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 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?
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.
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
这篇关于具有相同名称的Django模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!