11

I don't want use url_for('static', file_name='foo.jpg') to get static file in template.

how to get static file in this way:

<img src="/pic/foo.jpg" />

thanks

Cfreak
  • 19,191
  • 6
  • 49
  • 60
Robin
  • 634
  • 1
  • 7
  • 18
  • 3
    As long as `/pic/foo.jpg` exists it should work fine. Did you try it? – Cfreak Dec 04 '12 at 15:35
  • Just from curiosity - why don't want to use? :) – Ignas Butėnas Dec 04 '12 at 18:43
  • @Cfreak thank you , it's works fine. i write the wrong path before. – Robin Dec 05 '12 at 03:17
  • @IgnasB. i think common path more convenient and intuitive for FE, what's your point – Robin Dec 05 '12 at 03:26
  • @Robin, well just asked :) I thought maybe you spotted some performance issue or something. I always prefer to have dynamic things, just in case I will change static dir to another or smth, so I don't ned to worry then about the some time ago created template which I already forgot to exist :) But this is everyone's choice ;) – Ignas Butėnas Dec 05 '12 at 06:20
  • i've just had the same problem and solved it like that: http://stackoverflow.com/a/29521067/303114 – danfromisrael Apr 09 '15 at 09:46
  • i just had a similar issue and i solved like that: http://stackoverflow.com/a/29521067/303114 notice it's quite similar to what i_4_got is suggesting just using add_url_rule method instead of the route – danfromisrael Apr 09 '15 at 09:52

1 Answers1

17

You can set up your own route to serve static files. Add this method and update the static path directory in the send_from_directory method, then your img tag should work.

@app.route('/pic/<path:filename>')
def send_pic(filename):
    return send_from_directory('/path/to/static/files', filename)

For a production app, you should set up your server to serve static files directly. It would be much faster and use less server resources, but for a few users the difference shouldn't be a problem.

alexwlchan
  • 5,699
  • 7
  • 38
  • 49
i_4_got
  • 918
  • 9
  • 10