10👍
for the record, it is considered a bad practice… but you can do this
{% with "products" as menu %}
{{ menu }}
{% endwith %}
Since that doesn’t actually solve your specific problem here is a possible application…
<div class='menu'>
{% block menuitems %}
<a class='{% ifequal menu 'products' %}selected{% endifequal %}' href='/whereever/'>products</a>
...
{% endblock %}
</div>
and in the child template
{% block menuitems %}
{% with 'products' as menu %}
{{ block.super }}
{% endwith %}
{% endblock %}
9👍
The context you pass within you view is also available in the templates you’re extending. Adding a ‘menu_class’: ‘selected’ in the context, you could set
<div id="menu" class="{{ menu_class }}">
in the base template.
Another way around would be
<div id="menu" class="mymenu {% block menu_attrib %}{% endblock %}">
which then is extendible in your child template by
{% block menu_attrib %}selected{% endblock %}
- RuntimeError: Never call result.get() within a task Celery
- Django Rest Framework: How to enable swagger docs for function based views
1👍
There is more than one answer here of course!
You could use custom template tags to both draw the menu and select the appropriate one.
So your template tag would be:
{% mymainmenu selecteditem %}
Have a look at the custom template tag documentation on the django site, but it would end up something like:
@register.simple_tag
def mymainmenu(selecteditem):
html = ''
build the html for the menu here and include selected class
return html
- Why __unicode__ doesn't work but __str__ does?
- Django – Difference between Database backed sessions and Cookie Based Session?
- What is Django's TEMPLATE_DEBUG setting for?
0👍
Thanks everyone – in the end I followed speakman’s suggestion and put the name of the current menu option in thew context and use my:
{%ifequal menu "products" %}
class="selected"
{% endifequal %}
clause in each menu opton.
I don’t think this is a great solution, it couples my ‘views’ to my ‘templates’ more than I would have liked…but maybe this is just s django quirk
0👍
You can use a custom template tag as described here:
http://www.soyoucode.com/2011/set-variable-django-template
- How to output text from database with line breaks in a django template?
- How to access an attribute of an object using a variable in django template?
- Django: IntegrityError during Many To Many add()
- Check for request.GET variable in the template
- How to disable HTML encoding when using Context in django