Skip to content

Instantly share code, notes, and snippets.

@uranusjr
Last active December 17, 2015 08:08
Show Gist options
  • Save uranusjr/5577378 to your computer and use it in GitHub Desktop.
Save uranusjr/5577378 to your computer and use it in GitHub Desktop.
A tag that injects any output of another template tag into current context. Syntax: `{% inject as variable_name from tag_name [tag_arg ...] %}` where `variable_name` if the key to inject into, `tag_name` is the name of tag to retrieve value from, and `tag_arg`s are parameters to be used in the tag specified by `tag_name`.
from django.template import (
TemplateSyntaxError, Library, Node, Variable, Token, TOKEN_BLOCK
)
register = Library()
@register.tag(name='inject')
def inject(parser, token):
"""
A tag that injects any output of another template tag into current context.
Syntax: `{% inject as variable_name from tag_name [tag_arg ...] %}` where
`variable_name` if the key to inject into, `tag_name` is the name of tag to
retrieve value from, and `tag_arg`s are parameters to be used in the tag
specified by `tag_name`.
Example usage:
{% inject "result" from "now" "jS F Y H:i" %}
It is {{ result }}.
"""
parts = token.split_contents()
name = parts[0]
var_name = parts[1]
if parts[2] != 'from':
syntax_error_msg = (
'{name} tag requires syntax `{name} as <variable_name> from '
'<tag_name> [tag_args ...]`'
).format(name=name)
TemplateSyntaxError(syntax_error_msg)
tag_name = parts[3]
return InjectNode(tag_name, var_name, parser, parts[4:])
class InjectNode(Node):
def __init__(self, tag_name, var_name, parser, parts):
super(InjectNode, self).__init__()
self.var_name = var_name
self.tag_name = tag_name
self.parts = parts
self.parser = parser
def render(self, context):
tag_name = Variable(self.tag_name).resolve(context)
tag = self.parser.tags.get(tag_name, None)
self.parts.insert(0, tag_name)
token = Token(TOKEN_BLOCK, ' '.join(self.parts))
result = tag(self.parser, token).render(context)
var_name = Variable(self.var_name).resolve(context)
context[var_name] = result
return ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment