Method Analysis of Defining Variables of set variable in django template in django Framework Template

  • 2021-07-01 07:44:14
  • OfStack

This paper illustrates the method of defining variables in django framework template. Share it for your reference, as follows:

There are always cases where you want to set temporary variables in django template, but django doesn't have a good out-of-the-box tag or filter for assigning temporary variables in templates. But it can still be achieved by 1 other methods.

1. Using the with tag of django
2. Use custom tag implementation, should be much more flexible.

Using with tag of django to assign values to variables

It seems that this approach was supported after django 1.3

Get the value from context for assignment


{% with total=business.employees.count %}
  {{ total }} employee{{ total|pluralize }}
{% endwith %}

Of course, you can also give a constant directly


{%with age=100%}
{{ age|add:"2" }}
....
{%with%}

2 Custom Label Method Assign Values to Variables in django template


from django import template
register = template.Library()
class SetVarNode(template.Node):
  def __init__(self, var_name, var_value):
    self.var_name = var_name
    self.var_value = var_value
  def render(self, context):
    try:
      value = template.Variable(self.var_value).resolve(context)
    except template.VariableDoesNotExist:
      value = ""
    context[self.var_name] = value
    return u""
def set_var(parser, token):
  """
    {% set <var_name> = <var_value> %}
  """
  parts = token.split_contents()
  if len(parts) < 4:
    raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}")
  return SetVarNode(parts[1], parts[3])
register.tag('set', set_var)

When applied in template, the file where the tag load is located in the template now. It is then processed in a manner similar to the following


{% load set_var %}
{% set a = 3 %}
{% set b = some_context_variable %}
{% set c = "some string" %}

In this way, variables are assigned and processed in django template.

I hope this article is helpful to the Python programming based on Django framework.


Related articles: