1

I have this issue hope you have some idea how to solve it. In a Django templates which is not a "child" template of base template, I would like to use javascript modules which are in the base template, i.e. Jquery. Is there a way to achieve this without load again all javascript libraries I need?

Lets say base.html

{% block js %}  
<script src="some/path/to/jquery.js"></script>
{% endblock $}

some_component_base_template.html

// Not inherited from base.html

{% block somejsblock %}
<script>
$(document).ready(function(
   //some code I need
))
</script>
{% endblock %}

This block of html can be inserted anywhere in the template by user via slots mechanisms, this is why it doesn't inherit from base.html, if I create another header, every time that this block of html is loaded, javascripts are going to be loaded too.

2 Answers2

2

The template should inherit from base, then. If there's stuff currently in base you don't want to be in some other templates, you should use an intermediate parent which itself inherits from base and which some templates can use and others don't.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

If you are not inheriting from the base you should create a header and add the reference there manually.

acostela
  • 2,597
  • 3
  • 33
  • 50
  • this is what I want to avoid, because this is a piece of html that is going to be repeated all around the site, and in this case, I will be using a google api, whenever its load more than once, I get an javascript error or warning. Aren't javascript modules globally available? – Jose Romero Sep 04 '15 at 08:58
  • In that case the best answer is Daniel Roseman's one. You should put in your base only all the globals stuffs. In case you need different things that will be repeated over the app, the best that you can do is create an "intermediate" parent that extends from base and add theses new pieces of htmls. – acostela Sep 04 '15 at 09:03
  • "this is a piece of html that is going to be repeated all around the site" : then obviously it should be part of the base template as Daniel Roseman said - that's what the base.html template is for: parts that you want on _each and every_ template. – bruno desthuilliers Sep 04 '15 at 09:43