用jinja从静态文件夹导入javascript文件 [英] Import javascript files with jinja from static folder
问题描述
我需要在javascript文件中访问jinja模板(由于i18n标签)。所以我发现的方式只是从jinja方法加载包含的js文件。 {%includefile.js%}
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" %}
然而这个方法只会在模板文件夹中寻找文件。但是js文件必须在静态文件夹中。我的问题是,我怎样才能改变如何jinja寻找文件的方式?
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 %}
推荐答案
示例目录结构,看起来像这样
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
当您创建应用程序对象时,您可以设置瓶颈 static_url_path
You can set the flask static_url_path
when you create the app object
app = Flask(__name__, static_url_path='/static')
然后在 test_page.html
中,您可以看到如下所示的内容
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'm an html body
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
这篇关于用jinja从静态文件夹导入javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!