You can store a context variable with @register.simple_tag which returns simple data instead of returning a complicated Node
class based object as shown below:
# "custom_tags.py"
from django.template import Library
register = Library()
@register.simple_tag(takes_context=True)
def person(context):
context["name"] = "John"
context["age"] = 36
return ""
# "index.html"
{% load custom_tags %}
{% person %}
{{ name }} {{ age }}
Output:
John 36
In addition, you can store the return value from @register.simple_tag
's person()
to person_info
with as
argument as shown below:
# "custom_tags.py"
@register.simple_tag(takes_context=True)
def person(context):
return "John 36"
# "index.html"
{% load custom_tags %}
{% person as person_info %}
{{ person_info }}
Output:
John 36
And, you can store a context variable with @register.tag which returns a complicated Node
(class) based object as shown below. *@register.tag
cannot accept takes_context
argument otherwise there is an error and doesn't work with as
argument:
# "custom_tags.py"
from django.template import Library, Node
register = Library()
@register.tag
def person(parser, token):
return PersonNode()
class PersonNode(Node):
def __init__(self):
pass
def render(self, context):
context["name"] = "John"
context["age"] = 36
return ""
# "index.html"
{% load custom_tags %}
{% person %}
{{ name }} {{ age }}
Output:
John 36