eandersson
eandersson

Reputation: 26352

custom location for templates and static resources in flask

I am trying to figure out how to specify the location of html templates and static files like for example javascript files for Flask.

I currently have a structure to allow modules to be loaded like this

/wsgi
  /templates
         /login.html
         /logout.html
         /menu.html
  /static
  /modules
         /helloworld
                   /module.html
                   /module.json
                   /module.js

I would like to be able to load for example the Javascript file using a template directly without having to move it to the static folder.

Ideally I would like to do something like this

moduleHtml  = render_template(moduleHtmlPath)

and inside the template

<script type=text/javascript src="{{ url_for('myModule', filename='module.js') }}"></script>

Upvotes: 3

Views: 2510

Answers (1)

Rachel Sanders
Rachel Sanders

Reputation: 5884

If you're using Flask's blueprint functionality, you can have static files inside of the blueprint. Sort of like what you have, only you need to put them in a "static" folder. The doc has a pretty good example:

http://flask.pocoo.org/docs/blueprints/#static-files

helloworld = Blueprint('helloworld', __name__, static_folder='static')

and then refer to the static files in your templates like so:

url_for('helloworld.static', filename='module.js')

If you're not familiar with blueprints, it's worth reading up on them. They're pretty slick.

Otherwise, Flask has a built-in way to reference global static files, but they need to be in the root "static" directory:

http://flask.pocoo.org/docs/quickstart/#static-files

url_for('static', filename='module.js')

Upvotes: 5

Related Questions