Assign variable in Django Templates

I am learning Django by programming a site for tracking my workouts 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 and a file to store your tags for me mine was called

Inside that file you can setup a couple tags and use context to store the variable.

from django import template

register = template.Library()

def set_current_set_id(context,val):
   context["current_set"] = val
   return ""
def get_current_set_id(context):
    if context["current_set"] != None:
      return context["current_set"]
      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.

Leave a comment

Your email address will not be published. Required fields are marked *