if statement to determine which route is used in jinja template, flask

Viewed 667

I have two views which uses one template.

@users.route("/one")
@login_required
def one(username):
     return render_template('follower.html') 

and

@users.route("/two")
@login_required
def two(username):
     return render_template('follower.html') 

in the jinja template ( follower.html ), I am trying to execute a program if route one is used like this:

{% if url_for('users.one')  %}
    execute program
{% endif %}

but it seems I am doing it wrongly. Please what is the correct way of determine which route is used?

3 Answers

You can simply, in your template file, write a condition to check if request.endpoint equals the function name for the desired route, which in this case would be one, as seen in this example:

{% if request.endpoint == 'one'  %}
    execute program
{% endif %}

In this way, you will not make any changes to your route functions.

You cannot have two functions with the same name - they are both named two.

One simple way to accomplish this is to pass in a flag. E.g.,

@users.route("/one")
@login_required
def one(username):
    return render_template('follower.html', one=True)

then check for it in the template

{% if one %}
    execute program
{% endif %}

from two() you'd padd one=False.

Related