[Fixed]-Django template conditional variable assignment

8👍

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.

👤okm

4👍

Template tag:

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

Template:

{% alias sorted_users.0.username as menu_user %}

0👍

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.

👤Mikael

Leave a comment