I am trying to implement a django template tag {% domready %}{% enddomready %}that will contain its contents, remember it somewhere, and then a tag {% domready_render %}that will display all the contents.
It will look something like this:
{# main.html #}
<html>
...
<body>
...
<script>
(function($) {
$(document).ready(function() {
{% domready_render %}
});
})(jQuery);
</script>
</body>
</html>
{# some_other_file.html #}
{% extends main.html %}
..some html...
<a href="" id="link1">Link with onclick</a>
{% domready %}
$('#link1').click(function() { ... describe here your javascript ... });
{% enddomready %}
..some html...
<a href="" id="link2">Another with onclick</a>
{% domready %}
$('#link2').click(function() { ... describe here your another javascript ... });
{% enddomready %}
..some html...
And here is my question: how do I do this? I mean, this is what I tried to do:
@register.tag
def domready(parser, token):
nodelist = parser.parse(('enddomready',))
parser.delete_first_token()
return DomreadyNode(nodelist)
class DomreadyNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
if 'dom_ready' not in context:
context['dom_ready'] = []
context['dom_ready'].append(self.nodelist.render(context))
return ''
@register.tag
def domready_render(parser, token):
return DomreadyRenderNode()
class DomreadyRenderNode(template.Node):
def render(self, context):
if 'dom_ready' in context:
return u"\n".join(context['dom_ready'])
return ''
But this context ['dom_ready'] only works with the same template (I mean, what I can do {{ dom_ready }}in some_other_file.html, but I don’t see it in main.html (maybe because they have different visualization contexts or what?).
Thank.
source
share