I am learning Django by programming a site for tracking my workouts strengthnotes.com. I was struggling I needed to assign a variable to be used later in the template. It seems like this is not available by default in Django’s standard templates. I came across simple_tags and that seemed to fit the bill.
First step is create a templatetags directory at the same level as templates, migrations etc.
Inside that directory create a __init__.py and a file to store your tags for me mine was called workout_tags.py.
Inside that file you can setup a couple tags and use context to store the variable.
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def set_current_set_id(context,val):
context["current_set"] = val
return ""
@register.simple_tag(takes_context=True)
def get_current_set_id(context):
if context["current_set"] != None:
return context["current_set"]
else:
return "A99"
Then inside the template you can easily assign and retrieve the values.
{% set_current_set_id "A3" %}
{% get_current_set_id %}
This seems to work and reading the documentations this was the best method I could find.