Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created February 28, 2012 00:16
Show Gist options
  • Save yuchant/1928063 to your computer and use it in GitHub Desktop.
Save yuchant/1928063 to your computer and use it in GitHub Desktop.
Django capture contents of block - variable assignment in template like Shopify
"""
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 ''
@vdboor
Copy link

vdboor commented Apr 20, 2016

Thanks a lot for the code snippet! I've packaged this idea into a Python package: https://github.com/edoburu/django-capture-tag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment