6

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 4

6

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me - to be explicit, in the layout.html, add {% block scripts %} // {% endblock %} after the </body> (or wherever you want the scripts to load.)
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

Comments

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.