Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import javascript files with jinja from static folder [duplicate]

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 %}
like image 506
anvd Avatar asked Mar 29 '15 22:03

anvd


2 Answers

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 %}
like image 134
doekman Avatar answered Nov 10 '22 06:11

doekman


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.

like image 8
davidism Avatar answered Nov 10 '22 06:11

davidism