13

I need to have access to jinja template in javascript files (due to i18n tags). So the way that i found is just load the js file with include, from the jinja method. {% include "file.js" %}

However this method will look for files only in templates folder. But the js files must be in the static folder. My question is, how can i change the way how jinja looks for files? Instead of search in templates folder, in this case, search in the static folder.

{% block javascript %}
    <script type="text/javascript">
        {% include "myscript.js" %}
    </script>
{% endblock %}
anvd
  • 3,997
  • 19
  • 65
  • 126
  • you can use [`url_for('static', filename='script.js')`](http://flask.pocoo.org/docs/0.10/quickstart/#static-files) if you place your files in **static** dir – kartheek Mar 30 '15 at 06:37

3 Answers3

8

If you need to treat a file as a template, then it is not static. Put it in the templates folder and render it. If the file is not dynamic, then it is static. Put it in the static folder and link to it. There is no requirement that a given type of file must be a template or a static file. Pick whichever one is necessary.

On the other hand, it is probably better to keep JS static and pass arguments to it, rather than generating different code based on different input.

davidism
  • 121,510
  • 29
  • 395
  • 339
8

Given a example directory structure that looks like this

app/static/css/bootstrap.min.css
app/static/js/bootstrap.min.js
app/templates/test_page.html
app/views
run_server

You can set the flask static_url_path when you create the app object

app = Flask(__name__, static_url_path='/static')

and then in test_page.html you can have something that looks like this

<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">

 I am an HTML body

<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>

While it's not required to set the static URL path, since what's shown above is the default, I want to show it because it's a feature I didn't know about for a long time and can be useful.

Franco Roura
  • 807
  • 8
  • 26
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
8

You can create and register a global function just doing that:

import os

app = Flask(__name__.split('.')[0])

@app.template_global()
def static_include(filename):
    fullpath = os.path.join(app.static_folder, filename)
    with open(fullpath, 'r') as f:
        return f.read()

And then you can include it like this (the safe-filter prevents quotes begin escaped):

{% block javascript %}
    <script type="text/javascript">
        {{ static_include("myscript.js") | safe }}
    </script>
{% endblock %}
doekman
  • 18,750
  • 20
  • 65
  • 86