Skip to content

Instantly share code, notes, and snippets.

@MyGodIsHe
Last active August 29, 2015 14:18
Show Gist options
  • Save MyGodIsHe/b7f61e11719b7d96c07e to your computer and use it in GitHub Desktop.
Save MyGodIsHe/b7f61e11719b7d96c07e to your computer and use it in GitHub Desktop.
Django wrap tag
from django.template.base import Node, Library, TemplateSyntaxError, Context
from django.template.loader import get_template
register = Library()
class WrapControlNode(Node):
"""Implements the actions of the wrap tag."""
def __init__(self, filepath, nodelist):
self.filepath, self.nodelist = filepath, nodelist
def render(self, context):
content = self.nodelist.render(context)
filepath = self.filepath.resolve(context)
t = get_template(filepath)
return t.render(Context({'content': content}))
@register.tag
def wrap(parser, token):
"""
Wrap block.
# default-helper.html
<div class="popup">
<span class="close"></span>
<p>
{{ content }}
</p>
</div>
# index.html
{% wrap "default-helper.html" %}
Happy new year {% now 'Y' %}
{% endwrap %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'wrap' tag requires exactly one argument.")
filepath = parser.compile_filter(bits[1])
nodelist = parser.parse(('endwrap',))
parser.delete_first_token()
return WrapControlNode(filepath, nodelist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment