Context processors, am I doing them right?

31 views
Skip to first unread message

Dean De Leo

unread,
Feb 3, 2015, 7:56:09 PM2/3/15
to django...@googlegroups.com
Hi,
I am new to Django and I am still going through the tutorial. I've tried to set up a context processor for the following scenario, and I would like to obtain some confirmation if this is a proper solution or I am doing some mess..
In my base template with a header there is a navigation bar. A single button should be highlighted among the others depending in the current section / page in the website:

<ul>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/about" class="selected">Projects</a></li>
    ...
</ul>

What I thought so far was to register a universal context processor:

def navbar_selected_menu( request ):
    items = {"blog": "", "about": ""}
    target = request.META["PATH_INFO"]

    def select( key ):
        " Select the given key in the dictionary item "
        nonlocal items;
        items[key] = ' class="selected"';

    if re.match( "(^/$)|(^/blog$)|(^/blog/)", target):
        select("blog")
    if re.match(  "^/about\.s?html", target): # about
        select("about")


    return {"navbar": {"selected": items}};

and add to all links a variable such as <a href="/blog"{{ navbar.selected.blog }}>Blog</a>.

Is this solution appropriate or does it exist something clearer?

Moreover, is there the chance to pass explicitly a variable from the url mapping to the context processor ?

Kind regards,
Dean

Scot Hacker

unread,
Feb 4, 2015, 11:43:18 AM2/4/15
to django...@googlegroups.com, dean...@gmx.com


On Tuesday, February 3, 2015 at 4:56:09 PM UTC-8, Dean De Leo wrote:
Hi,
I am new to Django and I am still going through the tutorial. I've tried to set up a context processor for the following scenario, and I would like to obtain some confirmation if this is a proper solution or I am doing some mess..
In my base template with a header there is a navigation bar. A single button should be highlighted among the others depending in the current section / page in the website:

To me, this feels overly complex. Here's how I do current element selection in navigation, without context processors, by passing variables during the navigation's include statement. It does make templates a bit more verbose, but seems very clear and simple. 

In each page template:

{% block app_nav %}
{% include "dirapp/include/nav.html" with active_tab='something' %}
{% endblock app_nav %}

In the navigation:

<a href="{% url 'foo' %}"
    class="list-group-item {% if active_tab == 'something' %}active{% endif %}">Foo
</a>





Reply all
Reply to author
Forward
0 new messages