我正在编写一个FlASK应用程序,分为几个模块,每个模块驻留在一个单独的文件夹中,该文件夹包括‘Templates’和‘Static’文件夹.
在每个模块中,我将一个全局变量‘Custom_js’传递给模板:
module_bp = Blueprint('module', __name__, template_folder='templates', static_folder='static')
# pass custom js files to the base template
@module_bp.context_processor
def custom_js_context():
return {'custom_js': ['some_file.js']}
我在主模板base.html中包含了以下这些JavaScript文件:
{% if custom_js %}
{% for js_file in custom_js %}
<script src="{{ url_for('static', filename='js/' + js_file) }}"></script>
{% endfor %}
{% endif %}
上面的代码导致添加到base.html.物理文件位于/MODULE/STATIC/js/ome_file.js,但是访问http://127.0.0.1:8080/static/js/some_file.js会导致404错误.
我如何才能正确地从模块提供这些JavaScript文件呢?
一种 idea 是修改蓝图,以:
module_bp = Blueprint('module',
__name__,
template_folder='templates',
static_folder='static',
static_url_path='/module/static'
)
并像这样将文件提供给模板:
@module_bp.context_processor
def custom_js_context():
custom_js_files = ['some_file.js']
custom_js_with_prefix = ['/module/static/js' + filename for filename in custom_js_files]
return {'custom_js': custom_js_with_prefix}
使用更新的base.html循环
{% if custom_js %}
{% for js_file in custom_js %}
<script src="{{ js_file) }}"></script>
{% endfor %}
{% endif %}
然而,我不确定这在多大程度上是正确的方法.