[Django]-Django: Passing argument to parent template

45šŸ‘

āœ…

Have you tried the {% with %} template tag?

{% block content %}
  {% with 'myvar' as expectedVarName %}
  {{block.super}}
  {% endwith %}
{% endblock content %}
šŸ‘¤czarchaic

9šŸ‘

Thereā€™s no direct way to pass a variable up the template inheritance tree the way you describe. The way that people implement navigation bars that highlight the current page is often tweaked to the nature of the site itself. That said, Iā€™ve seen two common approaches:

The low-tech approach

Pass a variable in the template context that indicates which tab is active:

# in views.py
def my_view(request):
    return render_to_response('app2_template.html', {"active_tab": "bar"},

<!-- Parent template -->
<div id="navigation">
    <a href="/foo" {% ifequal active_tab "foo" %}class="active"{% endifequal %}>Foo</a>
    <a href="/bar" {% ifequal active_tab "bar" %}class="active"{% endifequal %}>Bar</a>
</div>

The higher-tech approach

Implement a custom template tag to render your navigation bar. Have the tag take a variable that indicates which section is active:

<!-- Parent template -->

<div id="navigation">{% block mainnav %}{% endblock %}</div>

<!-- any child template -->
{% load my_custom_nav_tag %}
{% block mainnav %}{% my_custom_nav_tag "tab_that_is_active" %}{% endblock %}

You can pretty much go crazy from there. You may find that someone has already implemented something that will work for you on djangosnippets.org.

3šŸ‘

Inability to pass args on template inclusion is one of many failings of the Django template system.

I had to deal with an almost identical problem: Deeply nested templates needed to cause parent templates to format/highlight differently.

Possible solutions:

  1. Use a ā€œsuper contextā€ routine that sets a number of values based on where in the hierarchy you are. I.e. super_context = MySuperContext(request, other, values, etc.), where super_context is a dict you pass to the view (or to RequestContext). This is the most Django-thnonic(?) approach, but it means that presentation logic has been pushed back into the views, which feels wrong to me.

  2. Use the expr template tag to set values in the lower level templates. Note: this only works when you {% include %} a template because it must be evaluated before the inclusion occurs. You canā€™t do that with an {% extends %} because that must be the first thing in the child template.

  3. Switch to Jinja2 templating, at least for the views where you need to do this.

Once you have these values set you can do things like this:

<div class="foo{% if foo_active%}_active{%endif%}"> stuff </div>

This makes the div class ā€œfooā€ when itā€™s not active and ā€œfoo_activeā€ when it is. Style to taste, but donā€™t add too much cinnamon. šŸ™‚

šŸ‘¤Peter Rowell

2šŸ‘

I have taken Jarret Hardieā€™s ā€œlow techā€ approach in a similar, errā€¦ context (yes, itā€™s a punā€¦ which wonā€™t make perfect sense to you unless I tell you that I was not doing navs but setting the border color of buttons in order to show which one had been pressed).

But my version is a bit more compact I think. Instead of defining just one simple context variable activebar in the view, I return a dictionary, but always with only one key-value pair: e.g. activebar = {ā€˜fooā€™: ā€˜activeā€™}.

Then in the template I simply write class=ā€{{activebar.foo}}ā€ in the foo anchor, and correspondingly in the other anchors. If only activebar.foo is defined to have the value ā€œactiveā€ then activebar.bar in the bar anchor will do nothing. Maybe ā€œfail silentlyā€ is the proper Django talk. And Bobā€™s your uncle.

EDIT: Oopsā€¦ a couple of days have passed, and while what I had written above did work for me a problem appeared when I put into the navbar an anchor with a new window as target. That seemed to be the cause of a strange glitch: after clicking on the new window (tab in Firefox) and then returning to the one from which the new window was launched, portions of the display below the navbar became blank whenever I quickly moved the cursor over the items on the navbarā€” without clicking on anything. I had to force a screen redraw by moving the scroll bar (not a page reload, though that too worked because it involves a screen redraw).

Iā€™m much too much of a noob to figure out why that might happen. And itā€™s possible that I did something else that caused the problem that somehow went away. Butā€¦ I found a simpler approach thatā€™s working perfectly for me. My circumstances are that every child template that is launched from a view should cause an associated navbar item to be shown as ā€œactiveā€. Indeed, that navbar item is the one that launched the view that launched the child templateā€” the usual deal.

My solutionā€” letā€™s take a ā€œloginā€ navbar item as an exampleā€” is to put this in the child template that contains the login form.

{% block login %}active{% endblock %}

I put it in below the title block but I donā€™t suppose the placement to matter. Then in the parent template that contains the navbar definition, for the li tag that surrounds the anchor for the login navbar item I putā€¦ well, hereā€™s the code:

<li class="{% block login %}{% endblock %}"><a href="/mysite/login">Login</a></li>

Thus when the child template is rendered the parent will show the login navbar item as active, and Bobā€™s still your uncle.

The dictionary approach that I described above was to show which of a line of buttons had been pressed, when they were all on the same child template. Thatā€™s still working for me and since only one child template is involved I donā€™t see how my new method for navbars would work in that circumstance. Note that with the new method for navbars views arenā€™t even involved. Simpler!

1šŸ‘

Variables from the parent template are automatically included in the childā€™s scope. Your title says you want to pass a variable TO the parent, which doesnā€™t make sense, as you canā€™t define variables in templates. If you need it a variable in the both the parent and the child, just declare it in the view.

1šŸ‘

Sadly I canā€™t find a clean way.

Ended up putting a tag in each appā€™s base.html:

<span class="main_nav_bar_hint" id="2"></span>

(Actually I use two. One set by appā€™s base for the main nav. One set by app pages for appā€™s nav bar)

And a bit of JQuery magic in the project base.html

$(document).ready(function() { $("#nav_menu_" + $(".main_nav_bar_hint").attr("id")).removeClass("normal").addClass("selected"); })

Its a bit of a hack, but this way its easy to understand and I only need to make logical changes once more apps are added.

šŸ‘¤Boris

-1šŸ‘

You can use HttpRequest.resolver_match.

In the parent html template:

<li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:homepage' %}active{% endif %}"><a href="{% url 'my_simple_blog:homepage' %}" class="nav-link">Home</a></li>
<li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:about' %}active{% endif %}"><a href="{% url 'my_simple_blog:about' %}" class="nav-link">About</a></li>

It checks for the current namespace and compare it, if they are the same, add active in the class of the list.

šŸ‘¤azmirfakkri

Leave a comment