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 %}
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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With