5

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.

simanacci
  • 2,197
  • 3
  • 26
  • 35
user2300867
  • 593
  • 1
  • 12
  • 28

4 Answers4

5

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 %}
Santosh Kumar
  • 26,475
  • 20
  • 67
  • 118
belvederef
  • 2,195
  • 19
  • 16
  • 2
    This worked for me - to be explicit, in the `layout.html`, add `{% block scripts %} // {% endblock %}` after the `

    ` (or wherever you want the scripts to load.)

    – BruceWayne Apr 11 '19 at 17:43
1

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

Sumedh Junghare
  • 381
  • 2
  • 4
  • 21
0
{% block javascript %}
<script type="text/javascript">
    {% include "some-js-file.js" %}
</script>
{% endblock %}

Create a code block like the block above.

For completeness, you can also reference this SO question: Loading external script with jinja2 template directive

tlm
  • 952
  • 10
  • 20
0

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>
simanacci
  • 2,197
  • 3
  • 26
  • 35