我正在编写一个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 %}

然而,我不确定这在多大程度上是正确的方法.

推荐答案

这就是我解决这个问题的方法(我不知道这是不是FlaskTM的普通方法):

    _controller_name_ = "bugsandfeatures"
    _url_prefix_ = '/' + _controller_name_

    bp = Blueprint("bugsandfeatues", __name__,
                   template_folder='templates',
                   static_folder="static",
                   url_prefix=_url_prefix_)

请注意url_前缀,它确保蓝图实际上从其自己的路径提供静态文件(请参见[https://flask.palletsprojects.com/en/3.0.x/blueprints/#static-files][1]).

现在,您可以:

    @bp.context_processor
    def custom_js_context():
        return {'custom_js': url_for('.static', filename='my_file.js')}

请注意"."在静电面前.它确保通过当前蓝图解析端点. 当您 Select 模板中的变量时,您会得到‘’/bugandFeature/Static/my_file.js‘’. [1]:https://flask.palletsprojects.com/en/3.0.x/blueprints/#static-files

Python相关问答推荐

ValueRight:参数目标和输出必须具有相同的形状.接收:目标.形状=(无,512),输出.形状=(无,3)

Flask:如何在完整路由代码执行之前返回验证

使用Python OpenCV的文本检测分割

Polars -转换为PL后无法计算熵.列表

pyautogui.locateOnScreen在Linux上的工作方式有所不同

未删除映射表的行

有症状地 destruct 了Python中的regex?

发生异常:TclMessage命令名称无效.!listbox"

Telethon加入私有频道

使用groupby Pandas的一些操作

如何在python polars中停止otherate(),当使用when()表达式时?

Python中绕y轴曲线的旋转

对象的`__call__`方法的setattr在Python中不起作用'

Python+线程\TrocessPoolExecutor

driver. find_element无法通过class_name找到元素'""

Python列表不会在条件while循环中正确随机化'

Pandas GroupBy可以分成两个盒子吗?

如何合并两个列表,并获得每个索引值最高的列表名称?

导入错误:无法导入名称';操作';

pandas fill和bfill基于另一列中的条件