Justin
Justin

Reputation: 1479

Using context variable to name a "section" instead of passing a value

In the following view, the context variable is used to mark the 'section' as 'dashboard'(I think).

@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html', {'section': 'dashboard'})

This then allows me to say {% if section == 'whatever' %}, for example:

{% if request.user.is_authenticated %}
      <ul class = 'menu'>
        <li {% if section == 'dashboard' %} class='selected' {% endif %}>
          <a href="{% url 'dashboard' %}">My Dashboard</a>
        </li>
        ... continues
    </ul>
   {% endif %}

Now if the dashboard view is called, .selected will be applied to the 'Dashboard' link (change color to show it's active). I get what it is doing, just don't understand how this works. I have only seen values passed in the context i.e. {'number': 8}. How exactly does django keep track of this naming system? It does not seem to be adding a class or anything of the sorts.

Upvotes: 0

Views: 91

Answers (1)

ivissani
ivissani

Reputation: 2664

Every key in the context dictionary that is passed to the template is transformed into a variable with that very same name that is available to the template at the moment of rendering.

For example if you render a template with a context dict such as:

{
    'key1': 'somevalue1',
    'key2': 'somevalue2',
    'key3': 'somevalue3',
}

in the template, at rendering time, you will have three variables called key1, key2 and key3 with the corresponding values.

So what is happening in your code is that when you call the view dashboard() this view renders the template your view calls the render() method which in turn takes the template code defined in the html file you pass to it and converts this code into pure html by executing the django template code in a context where a variable section has been created and assigned the value 'dashboard' (because that's what you passed to render() as the context param)

Upvotes: 1

Related Questions