bernie2436
bernie2436

Reputation: 23931

How do I add a link to a static file in an a flask/jinja HTML template?

I am learning flask. I understand that to generate a url for a static file at /static/style.css, I do this url_for('static', filename='style.css'). I also understand that I can use a template to generate HTML, with render_template('hello.html', name=name) which will return the HTML output from a jinja template at templates/hello.html.

However, I am not sure how to return a link to a static file in a jinja template -- or if this is even how I am supposed to go about returning HTML that links to static HTML/CSS.

Basically, how do I return a link to a URL generated dynamically with python within a jinja template? This seems impossible. So what do people do? If you just put a link in the template it looks for the static file at host/URLThatDisplaysTemplate/PathToStaticFileInTheLink instead of host/PathToStaticFileInTheLink, which is what I want.

Upvotes: 0

Views: 3054

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

Just use url_for() in the template:

{{ url_for('static', filename='style.css') }}

Flask adds url_for() to the template globals, so it is always available.

Upvotes: 6

Related Questions