7

I want to check that my dummy.csv exist or not in my local system. If it exist then this Check Fraud Status will be displayed otherwise it won't. I don't want to use Javascript. If any solution relating to python jinja then please help me out.

And one more thing how to import os in html page using jinja?

I had tried this:

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 %}

error

jinja2.exceptions.UndefinedError: 'os' is undefined
Rahul Rahatal
  • 648
  • 5
  • 19
Ritul Chavda
  • 173
  • 1
  • 9

2 Answers2

5

Add this in main.py file which contains import os module.

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 %}

It worked for me. Hope it help to others.

Ritul Chavda
  • 173
  • 1
  • 9
3

Another way to check for the file existence is to define a custom function for this.

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))
therceman
  • 231
  • 1
  • 6