Import javascript files with jinja from a static folder

I need to have access to the jinja template in javascript files (due to i18n tags). So, the way I found is to download the js file using the jinja method. {% include "file.js" %}

However, this method will only search for files in the templates folder. But js files should be in a static folder. My question is, how can I change the way jinja files are searched? Instead of searching in the templates folder, in this case, search in the static folder.

 {% block javascript %} <script type="text/javascript"> {% include "myscript.js" %} </script> {% endblock %} 
+6
source share
3 answers

Given an exemplary directory structure that looks like

 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 jar static_url_path when creating the application object

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

and then in test_page.html you can have something similar to this

 <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet"> I'm an html body <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script> 
+5
source

If you need to process the file as a template, then it is not static. Put it in the templates folder and render. If the file is not dynamic, it is static. Put it in a static folder and a link to it. There is no requirement that this file type be a template or a static file. Choose the one you need.

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

+4
source

You can create and register a global function, just:

 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 enable it like this ( safe -filter prevents quotes from running):

 {% block javascript %} <script type="text/javascript"> {{ static_include("myscript.js") | safe }} </script> {% endblock %} 
+1
source

Source: https://habr.com/ru/post/984402/


All Articles