3

I'm having a problem where Jinja is treating a variable I'm passing to it as a literal string, which screws up the URL routing work done by Flask.

app.py - each "course" has its designated URL, as shown by /course/<name>.

@app.route("/course/<name>")
@login_required
def course(name):
    collection = mongo.db.courses
    course = collection.find_one({"name": name})
    return render_template("course.html", course=course)

profile.html - These "courses" will be displayed on the profile.html page, and they should have href tags that lead them to the appropriately rendered course.html page.

Attempt #1: I tried passing in {{ course }} into the name parameter, but the URL was messed up as Jinja treated it as a string altogether.

{% for course in courses %}
  <div class="col-md-4">
    <div class="panel panel-default">
      <div class="panel-body">
        <a href="{{ url_for('course', name='{{ course }} }}">{{ course }}</a>
      </div>
    </div>
   </div>
{% endfor %}

Attempt #2: I tried setting up a Jinja variable and passing that to the href tag, but this did not work as well.

{% for course in courses %}
  <div class="col-md-4">
    <div class="panel panel-default">
      <div class="panel-body">
        {% set url = url_for('course', name="{{ course }}") %}
        <a href="{{ url }}">{{ course }}</a>
      </div>
    </div>
   </div>
{% endfor %}

How can I dynamically generate new href tags for each course variable without having Jinja treat the href tags as a literal string?

Shrey
  • 522
  • 8
  • 16

1 Answers1

2

{{ begins a block of Python code. Things you do inside it follow Python behavior rules, not those of Jinja. You are passing the value {{ course }} as name to url_for. Just use course as a variable.

{{ url_for('course', name=course.name) }}
dirn
  • 19,454
  • 5
  • 69
  • 74