Flask - Different Javascript file for each template

Viewed 5095

I'm working on an application built with flask and using templates. I have a layout.html file with head tags and js/css links which I'm importing on each page using:

{% extends "layout.html" %}
{% block content %}
    {# My content #}
{% endblock content %}

This works but I now need to link to other JS files only for specific html files and wondering what is the correct way of doing it using flask.

4 Answers

You can simply include your <script> tags in the HTML file where you need them. This way, the javascript will be imported only when that specific page is loaded.

An example is:

{% extends "layout.html" %}
{% block content %}
   {# My content #}
{% endblock content %}
{% block scripts %}
  <script scr="..."></script>
{% endblock scripts %}

If I am not wrong, you want some of your HTML pages to have a link to JavaScript code. To achieve this just add the <script> tag in that particular HTML page as follows:

<script src="{{ url_for('static', filename='JS/some_file.js') }}"></script>

where- JavaScript file is kept at: static->JS->some_file.js

You can have all the unique Javascript tags in the layout.html file then for each endpoint use if else statements to render the tag you want for each page. The endpoint is simply the name of the view function.

{% if request.endpoint == 'index' %}
    <script src="{{ url_for('static', filename='JS/file.js') }}"></script>
{% elif request.endpoint == 'another-endpoint' %}
    <script src="{{ url_for('static', filename='JS/some_other_file.js') }}"></script>
Related