6

I tried to read file print.html that located in path: templates/print.html.

So, I used url_for() to refer to it as below:

{{ url_for('templates', filename='print.html') }}

However, I got an error as below Traceback:

BuildError: ('templates', {'filename': 'print.html'}, None)

What's wrong with this?

If I used {{ url_for('static', filename='print.html') }}, it just working find. However, file that I tried to read is not in static folder, it was in templates/print.html instead.

How can I use url_for() to read my file print.html in templates folder? Thanks.

davidism
  • 121,510
  • 29
  • 395
  • 339
Houy Narun
  • 1,557
  • 5
  • 37
  • 86

1 Answers1

10

I'll start by saying-- if you're trying to url_for a template, it's likely you're misunderstanding a concept. But, assuming you're know the difference between a rendered template and a static asset:

You could build a route for the print.html:

@app.route('/print')
def print():
    return render_template('print.html')

Which would then enable you to url_for('print') to get the resolved url, and any dynamic components in your print.html template would get rendered to static html.

Otherwise, if the print.html is truly static-- just move it to the static folder, and use the url_for('static', filename='print.html') as you've indicated.

There's a handy Flask blueprint pattern that's useful if you're just rendering off a bunch of templates and don't need any view logic, see it here

Doobeh
  • 9,280
  • 39
  • 32
  • thanks for pointing that out. By the way, `return render_template('print.html')` would render template `print.html` directly on browser, yet I am trying to read content of `print.html` that would include `html` tags as well. Reason I put it in templates folder, because `print.html` contain some `macro` definitions that it is called to use in another template, `{% from "print.html" import any_macro %}`. Thanks. – Houy Narun Feb 06 '18 at 20:29