How to set a value of a variable inside a template code?

后端 未结 9 1245
我寻月下人不归
我寻月下人不归 2020-11-27 09:55

Say I have a template


Hello {{name}}!

While testing it, it would be useful to define the

9条回答
  •  攒了一身酷
    2020-11-27 10:30

    The best solution for this is to write a custom assignment_tag. This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

    Start by creating a template tag file (eg. appname/templatetags/hello_world.py):

    from django import template
    
    register = template.Library()
    
    @register.assignment_tag
    def get_addressee():
        return "World"
    

    Now you may use the get_addressee template tag in your templates:

    {% load hello_world %}
    
    {% get_addressee as addressee %}
    
    
        
            

    hello {{addressee}}

提交回复
热议问题