[Django]-Writing script tag outside or inside block?

5👍

The first one executes successfully but the second one does not. Is it necessary to load an external static file from inside a django template block and if not then why does the second code not execute?

If you override a basic template, you can only “fill the blocks” so to speak. Where is Django supposed to write the things you write outside the blocks? At the beginning of the file? At the end of the file? Somewhere in between?

As specified in the documentation on template inheritance [Django-doc]:

The most powerful – and thus the most complex – part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

You can however define multiple blocks. For example it is common to add a block at the end where you can optionally add some extra JavaScript in, like:

<!--templates/base.html-->
{% load static %}
<html>
  <head><title>Django Blog</title>
    <link href="{% static 'css/base.css' %}" rel="stylesheet">
  </head>
  <body>
    <header><h1><a href="{% url 'home' %}">Django Blog</a></h1></header>
    <div>
      {% block content %}
      {% endblock content %}
    </div>
  {% block js %}
  {% endblock %}
  </body>
</html>

So then you can write the <script ...> part at the bottom of the page, like:

{% extends 'base.html' %}
{% load static %}

{% block content %}
  {% for post in object_list %}
  <div class='post-entry'>
    <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2>
      <p>{{ post.body }}</p>
  </div>
  {% endfor %}
{% endblock %}

{% block js %}
<script type="text/javascript" src="{% static 'js/test.js' %}"></script>
{% endblock %}

You can of course define variables, etc. outside the {% block ...%} ... %{ endblock %} parts. But everthing that is rendered outside is ignored if you inherit from a base template.

1👍

for the second script, you are specifying the src attribute of the script element using a django command {% static 'js/test.js' %}, for that to work it needs to be inside a django block,

if you want to do this without using the django block, you need to specify the value of the src attribute without using a django commande, you should do it just as if you are working only with html,

<script type = "text/javascript" src = "path_to test.js"></script>

Leave a comment