Reputation: 3418
In my base.html template which is imported in every Django template, I have a block with the Google Analytics script:
<!-- GOOGLE ANALYTICS -->
<script type="text/javascript">
bla bla...
</script>
I would like to have this script only included when in production, but not during development. Is there a solution for this comparable to the solution in setting.py?
import socket
if socket.gethostname() == 'my-laptop':
DEBUG = TEMPLATE_DEBUG = True
else:
DEBUG = TEMPLATE_DEBUG = False
Anybody who knows of a template tag, or should I do my own one?
Upvotes: 2
Views: 1929
Reputation: 1861
In settings.py
,Check debug
is True
, also add:
INTERNAL_IPS = (
'127.0.0.1',
'localhost',
)
Then you can use things in your template like this:
{% if debug %}
<span>This is debug</span>
{% else %}
<span>This is production</span>
{% endif %}
If want to change to production, set debug
to False
.
Ref: http://www.djangobook.com/en/2.0/chapter09.html
Upvotes: 3
Reputation: 66
I do the following on lots of sites and it seems to work really well.
Then in my static media file directory I have a copy of base.css and base_dev.css. I do all my development in the base_dev.css file then merge it into base.css before I launch.
Upvotes: 0
Reputation: 10697
The template is probably not the best place to handle this.
usually, you'd write a context preprocessor that will process the request and add a flag to your context (such as PRODUCTION = True). Then you can use a simple if statement in the template, or better yet, write a simple custom tag that will hide that implementation detail from the template.
See also this answer.
Upvotes: 0
Reputation: 1659
You could add your DEBUG variable to a context processor and just put an IF around that block. http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
from django.conf import settings
def debug_context(request):
return {'DEBUG': settings.DEBUG}
Then in your template:
{% if DEBUG %}
STUFF
{% endif %}
Alternatively you could make the context processor return anything you want to key off of, anything in your settings file or otherwise.
Upvotes: 4
Reputation: 86974
Haven't seen such a template tag yet.
I'm more inclined to use different setting.py files for production and dev, and include analytics code as described in this answer.
This solution allows for a simpler template, and gives you the option to use different analytics code in different deployments of the same app.
Upvotes: 0