Django template conditional variable assignment

前端 未结 3 1018
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 21:31

I want to assign a variable do different values depending on if a variable exists, is this possible? My non working example might make it clearer:

{% if user         


        
3条回答
  •  清酒与你
    2020-12-18 21:57

    update Then its better to customize a template tag like

    @register.inclusion_tag('menu_snippet.html')  # or you could use takes_context=True and fetch values from the context
    def render_menu(username, recent_users):
        if username:
            menu_user = username
        elif recent_users:
            # sorted here could be replaced by min or QuerySet method, it depends
            # for example: 
            # menu_user = min(recent_users, key=lambda u:u.timestamp).username
            menu_user = sorted(recent_users)[0]['username']
        return {'menu_user':menu_user}
    
    # in template, it looks like
    {% render_menu username recent_users %}
    

    Putting the code in the view is much better. Just as your pseudocode, clean and readable.

    If you still want to write template, I prefer something like

    {% if username %}
        
    {% else %}
        {% if recent_users %}
        {% with sorted_users=recent_users|dictsortreversed:"timestamp" %}
        {% with menu_user=sorted_users.0.username %}
        
        {% endwith %}{% endwith %}
        {% endif %}
    {% endif %}
    

    Depends on your actual usage, customized template tag or the include tag are also possibly useful.

提交回复
热议问题