如何在 html 页面中使用 jinja 检查系统中是否存在文件?

How to check file exist in system or not using jinja in html page?

我想检查我的 dummy.csv 是否存在于我的本地系统中。如果存在,则将显示此“检查欺诈状态”,否则不会显示。我不想使用 Javascript。如果有任何关于 python jinja 的解决方案,请帮助我。

还有一件事如何使用 jinja import os 在 html 页面中?

我试过这个:

layout.html

{% if os.path.exists('./static/userdata/dummy.csv') %}
   <a class="nav-item nav-link" href="{{ url_for('checkfraudstatus') }}">Check Fraud Status</a>
{% endif %}

错误

jinja2.exceptions.UndefinedError: 'os' is undefined

将此添加到包含导入 os 模块的 main.py 文件中。

main.py

import os

@app.context_processor
def handle_context():
    return dict(os=os)

layout.html

{% if os.path.exists('./static/userdata/dummy.csv') %}
     <a class="nav-item nav-link" href="{{ url_for('checkfraudstatus') }}">Check Fraud Status</a>
{% endif %}

它对我有用。希望对其他人有帮助。

检查文件是否存在的另一种方法是为此定义一个自定义函数。

from jinja2 import Template
import os


def path_exists(path):
    return os.path.exists(path)


template = Template("""
{% if path_exists('template.html') %} 
    File is found 
{% else %} 
    File not found 
{% endif %}
""")

print(template.render(path_exists=path_exists))