-1

I have read Loading external script with jinja2 template directive and Import javascript files with jinja from static folder but unfortunately no closer

I have a Python Flask site which is based on https://hackersandslackers.com/flask-blueprints/ so each blueprint has its own static and templates folder

My question is how would I include a JS file within a block that sits within a static/js folder of the blueprint?

pee2pee
  • 3,619
  • 7
  • 52
  • 133

1 Answers1

1

My suggestion is to set a separate static_url_path for each blueprint unless a url_prefix is defined. This adds a prefix to the URL where the static files will be loaded.

bp = Blueprint(
    'home', __name__,
    template_folder='templates',
    static_folder='static',
    static_url_path = '/home/static'
)

# ...
bp = Blueprint(
    'products', __name__,
    template_folder='templates',
    static_folder='static',
    url_prefix = '/products',
)

# ...

With the help of the request object, the name of the current blueprint can be determined. This can then be used to load the static file. Thus, a different file is loaded for each blueprint.

{% block javascript %}
  <script src="{{ url_for(request.blueprint+'.static', filename='js/main.js') }}"></script>
{% endblock %}

It is therefore necessary to adapt both the template_url_path or url_prefix and the identifier within url_for to the requirements.

Detlef
  • 6,137
  • 2
  • 6
  • 24