Created
February 28, 2012 00:16
-
-
Save yuchant/1928063 to your computer and use it in GitHub Desktop.
Django capture contents of block - variable assignment in template like Shopify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Capture contents of block into context | |
-------------------------------------- | |
Use case: variable accessing based on current variable values. | |
{% capture foo %}{{ foo.value }}-suffix{% endcapture %} | |
{% if foo in bar %}{% endif %} | |
Created on Monday, February 2012 by Yuji Tomita | |
""" | |
from django import template | |
register = template.Library() | |
@register.tag | |
def capture(parser, token): | |
nodelist = parser.parse(('endcapture',)) | |
parser.delete_first_token() | |
varname = token.contents.split()[1] | |
return CaptureNode(nodelist, varname) | |
class CaptureNode(template.Node): | |
def __init__(self, nodelist, varname): | |
self.nodelist = nodelist | |
self.varname = varname | |
def render(self, context): | |
context[self.varname] = self.nodelist.render(context) | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for the code snippet! I've packaged this idea into a Python package: https://github.com/edoburu/django-capture-tag