0

My layout template contains a header and I'd like to add a CSS class to the currently selected menu option.

class="active"

I thought I found the solution here but I'm still having issues. When I paste the following code into my template I get a server error.

{% rule = request.url_rule %}

Why didn't this work? How can I set a variable to control the menu in the templates?

Community
  • 1
  • 1
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

3 Answers3

3

{% rule = request.url_rule %} is not valid syntax in Jinja. If you want to set a context variable from a template, use set:

{% set rule = request.rule %}

request is already passed to each template context automatically, you don't need to pass it in render_template.

davidism
  • 121,510
  • 29
  • 395
  • 339
1

My best guess would be that the request object isn't getting passed to the template. If it isn't being passed you wouldn't be able to access it when rendering the template. You could pass it explicitly, which would look something like this:

from flask import request
from flask import render_template

@app.route('/hello/')
def hello():
    return render_template('hello.html', request=request)
neatnick
  • 1,489
  • 1
  • 18
  • 29
1

Someone commented that swankswashbucklers answer wouldn't fix my problem so I'm posting my solution which was inspired by his suggestion.

I simply manually set a variable called title when creating the view.

def home():
return render_template(
    'index.html',
    title='Home',
)

Within the template I referenced the variable to decide which menu item to highlight.

                    {% if title == "Home" %}
                    <li class="active">
                    {% else %}
                    <li>
                    {% endif %}

It turned out in my situation I didn't need to access the current url.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225