When you need to include a specific javascript file/code snippet in your page, it's always better to do it at the bottom of your page to avoid to block the rendering too soon. This tag provide you a nice way to include and launch only what is needed:
Example in an included template that need to display google maps:
{% dict js_file google_api %}
<script src="http://www.google.com/jsapi?key={{ MAPS_API_KEY }}" type="text/javascript" charset="utf-8"></script>
<script src="{{MEDIA_URL}}js/map.display.js" type="text/javascript">...</script>
{% enddict %}
{% dict js_code link_map %}
$('.show-map').click(function() {
...
});
$('.hide-map').click(function() {
...
});
{% enddict %}
Finaly you just have to add this to the very bottom of your base.html file:
....
</body>
{% for k,v in js_file.items %}
{{v}}
{% endfor %}
<script type="text/javascript">
/* <![CDATA[ */
{% for k,v in js_code.items %}
{{v}}
{% endfor %}
/* ]]> */
</script>
</html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from django.template import Library, TemplateSyntaxError
@register.tag(name='dict')
def do_dict(parser, token):
try:
tag_name, varname, key = token.contents.split(None, 2)
except ValueError:
raise TemplateSyntaxError("'dict' node requires a dict and a key name.")
nodelist = parser.parse(('enddict',))
parser.delete_first_token()
return DictNode(nodelist, varname, key)
class DictNode(Node):
def __init__(self, nodelist, varname, key):
self.nodelist = nodelist
self.varname, self.key = varname, key
def render(self, context):
output = self.nodelist.render(context)
# get the top level context
dict = context.dicts[len(context.dicts)-1]
if self.varname in dict:
dict[self.varname][self.key] = output
else:
dict[self.varname] = {self.key:output}
return ''
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
import statement should be:
from django.template import Library, TemplateSyntaxError, Node
#
Please login first before commenting.