Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

dynamic - Jinja dynamically nested variables

So i am trying to nest 2 variables in a url_for to pull a specific persons photo. This is my code

<img
  class="imgContainer"
  src="{{ url_for('static', filename='players/_{{player.username}}_.png') }}"
  />

My images are of the form 'username.png' so thats why I put the '_' at the beginning and end.

This is the Python part of it:

@app.route("/<username>")
def player(username):
    player = Player.query.filter_by(username=username).first()    
    return render_template("player.html",player=player)

What I tried:

  • {{ url_for('static', filename='players/_[player][username]_.png') }}
  • {{ url_for('static', filename='players/_player[username]_.png') }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When setting up your url_for, it's already contained in the {{ }}. So, you can break up your string + variables like this:

<img class="imgContainer"
    src="{{ url_for('static', filename='players/_' ~ player.username ~ '_.png') }}" />

Note the use of ~ to concatenate your variable and string within the {{ }} syntax. Using the ~ will convert your values to string first. If you know your variable types you can use +.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...