Django template conditional variable assignment

olofom picture olofom · May 28, 2012 · Viewed 18.5k times · Source

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 username %}
    {% with menu_user=username %}
{% elif recent_users %}
    {% with sorted_users=recent_users|dictsortreversed:"timestamp" %}
    {% with menu_user=sorted_users.0.username %}
{% endif %}
{% if menu_user %}
    <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>
{% endif %}
{% if recent_users %}
    {% endwith %}
{% endif %}
    {% endwith %}

Pseudocode of what I try to do:

if username:
    menu_user = username
elif recent_users:
    menu_user = sorted(recent_users)[0]['username']

if menu_user:
    <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>

Answer

okm picture okm · May 28, 2012

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.