Django template tags with same name

后端 未结 1 600
情话喂你
情话喂你 2021-01-13 18:13

For example I have 2 templatetags

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


        
1条回答
  •  孤城傲影
    2021-01-13 18:27

    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

    0 讨论(0)
提交回复
热议问题