Django template conditional variable assignment

前端 未结 3 1004
隐瞒了意图╮
隐瞒了意图╮ 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 %}
        <div id="menu">
            <ul>
                <li><a href="/user/{{ username|urlencode }}">Profile</a></li>
                <li><a href="/user/{{ username|urlencode }}/products/">Products</a></li>
            </ul>
        </div>
    {% else %}
        {% if recent_users %}
        {% with sorted_users=recent_users|dictsortreversed:"timestamp" %}
        {% with menu_user=sorted_users.0.username %}
        <div id="menu">
            <ul>
                <li><a href="/user/{{ menu_user|urlencode }}">Profile</a></li>
                <li><a href="/user/{{ menu_user|urlencode }}/products/">Products</a></li>
            </ul>
        </div>
        {% endwith %}{% endwith %}
        {% endif %}
    {% endif %}
    

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

    0 讨论(0)
  • 2020-12-18 22:02

    Template tag:

    @register.assignment_tag
    def alias(obj):
        """
        Alias Tag
        """
        return obj
    

    Template:

    {% alias sorted_users.0.username as menu_user %}
    
    0 讨论(0)
  • 2020-12-18 22:02

    Create a template tag that takes username and recent_users as arguments which then outputs the menu. That way you will keep your template clean from that kind of logic.

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