1

I am making a Django website. I am not an expert but I understand the basics. However I am a complete rookie when it comes to javascript. I am using Django Templates to have each page on my website 'inherit' from a Base page (base.html). I want to include Javascript within a script tag of the base page that will only load when a certain page is loaded. I want to do something like this:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  ...
  ...
</head>
<body>
  ...
  <!-- Main Content -->
  {% block content %}
  {% endblock %}
  ...

  <script> Some Script on every page </script>
  <!-- Some Django if statement like the one below goes here -->
  {% if this_page == '/special_page/' %}
    <!-- a special script is loaded here -->
    <script> Special Script </script>
  {% endif %}
</body>
</html>

I am not sure if this can be done. Can this be done, and if so, is it a security risk?

I do not know what javascript code I would need to make this happen if any is needed. So I am looking for a code-based solution if there is one.

BitWrecker
  • 174
  • 1
  • 10
  • Does this answer your question? [How to get the current URL within a Django template?](https://stackoverflow.com/questions/2882490/how-to-get-the-current-url-within-a-django-template) – funnydman Mar 09 '20 at 19:07
  • That helps a little bit, but I don't think its exactly what I am looking for. – BitWrecker Mar 09 '20 at 19:16

2 Answers2

0

One good way to handle this is to have the base template contain a block called something like javascript, then in child templates, you can do:

{% block javascript %}
  {{ block.super }} {# this loads the base js scripts #}
  {# put page-specific js here #}
{% endblock %}
nthall
  • 2,847
  • 1
  • 28
  • 36
  • Interesting approach. How would the 'page-specific js' know that it is on the page that it needs to be loaded on? – BitWrecker Mar 09 '20 at 19:20
  • generally you would specify which template to use in each view - cf. https://docs.djangoproject.com/en/3.0/topics/class-based-views/ – nthall Mar 10 '20 at 15:03
0

I would simply include a {%block page_specific_js %}{% endblock %} in your template.

Then, your "special page(s)" are the only ones which define any content for that block.

If you'd like for the special pages to include "the same content," you could let the special pages do something like this:

 {% block page_specific_js %}
   {% include "some file" %}
 {% endblock %}

... so, only the "special pages" define the block, and, when they do, they get the content from an included file (that all of them use).

The strong advantage of this approach, besides simplicity, is that it puts the rule of whether something else is included, and what that something-else is, into the special pages themselves. Which is where anyone would reasonably expect to find it. Meanwhile, the parent template shows where the content might be included, but doesn't say what it is.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41