'How to tell jinja about files in static sub-directories?

I have created a web app in which user uploads a image on my web app and that image is saved in myproject/static/uploads directory but I am unable to display that image.

my file upload code:

        file = request.files['file']
        filename = secure_filename(file.filename)
        if filename != '':
            file_ext = os.path.splitext(filename)[1]
            if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
                return 'Invalid Image', 400
            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

        post = Post(title=title,body=body,author_id=current_user.id,author=current_user,filename=filename)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.index'))
return render_template('blog/create.html')

my index view:

@bp.route('/')
def index():
   posts = Post.query.all()
   files = os.listdir(current_app.config['UPLOAD_FOLDER'])

   return render_template('blog/index.html', posts=posts, files=files)

index.html

{% block content %}


{% for post in posts %}
    <article class="post">
      <header>
        <div>
          <h1>{{ post.title }}</h1>
          <div class="about">by {{ post.author.username }} on {{ post.created.strftime('%Y-%m-%d') }}</div>
        </div>
      </header>
      <p class="body">{{ post.body }}</p>
    </article>
      {% for file in files %}
          <img src="{{ url_for('static', filename='uploads/post.filename') }}" style="width: fit-content;">
      {% endfor %}
      {% if not loop.last %}
        <hr>
      {% endif %}
  {% endfor %}
{% endblock %}


Solution 1:[1]

You have to use string concatenation to create the dynamic filename:

<img src="{{ url_for('static', filename='uploads/' ~ post.filename) }}" style="width: fit-content;">

The preferred operator is the tilde (~), but you can also use the plus operator if you wish.

Solution 2:[2]

You can simply do this in your main file:

app = Flask(__name__,
            static_url_path='', 
            static_folder='templates/static',
            template_folder='templates')

And then call your files: (path for 'example.js' is 'app/templates/static/js')

<img width="130" src="/js/example.js">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dauros
Solution 2