Yugal Jindle
Yugal Jindle

Reputation: 45636

Django : How to handle css/js specific to a template tag?

Background:

I have a css and a js that is used only by the Google maps template tag, that I include in my templates where-ever needed.

Inside template tag google_map:
...
...
return render_to_string('google_map.html', context)

Inside google_map.html I have the required css and the js :

<link rel="stylesheet" type="text/css" href="mystyle.css" />

My problem is :

I have a page with 3 maps, therefore 3 calls to the template tag. This implies the css and the js is included 3 times in the same page. [Should not happen]

Now, I can-not include these css and js in the header of the page, since all the pages are not having the maps so there, on all those pages it would be a burden.

What should I do, so that if a page has 3 or more maps, even then there is only a single include of the css & js and not repeated?

Upvotes: 2

Views: 2967

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239220

I'd recommend following the pattern introduced by Paul Irish for Markup-based unobtrusive comprehensive DOM-ready execution. There's a number of side benefits to the approach such as encapsulation, namespacing, etc., but the chief benefit for you would be conditional execution of JavaScript based on a id or class on <body>.

So in your base template change your <body> tag to something like the following:

<body class="{% block body_class %}{% endblock %}">

Then, for templates that need maps just do:

{% block body_class %}{% if block.super %}{{ block.super }} {% endif %}maps{% endblock %}

That looks a little complicated, but all it's doing is inheriting from the values any parent templates set for that block. The if block is used to conditionally include the space needed between multiple classes.

Finally, in your JavaScript you simply create a module for "maps" as the article describes and put all your map-specific JS there.

Upvotes: 5

nkryptic
nkryptic

Reputation: 86

You might use a new django block in the <head> section of your base template you extend:

<head>
  /* ... other css/js calls */
  {% block googlemapassets %}{% endblock %}
</head>

Then in the view template (assuming content is you main content block):

{% block content %}
  {% google_map %}
{% endblock %}
{% block googlemapassets %}
  <link rel="stylesheet" type="text/css" href="mystyle.css" />
{% endblock %}

Upvotes: 0

Related Questions