Python Expressions in Template Tags

Python expressions allow you to evaluate Python code directly in template tag attributes by wrapping the expression in parentheses. This provides a Vue/React-like experience for writing component templates.

Basic Examples

Negating a boolean

{% component "button"
  text="Submit"
  disabled=(not editable)
/ %}
Evaluates to True when editable is False

Conditional expressions

{% component "button"
  text="Delete"
  variant=(my_user.is_admin and 'danger' or 'primary')
/ %}
Ternary-like expression that evaluates to 'danger' when my_user.is_admin is True, otherwise 'primary'

Method calls and attribute access

{% component "button"
  text="Click Me"
  size=(name.upper() if name else 'medium')
/ %}
Uses string methods (.upper()) and conditionals to transform the name value

Complex Examples

Multiple Python expressions

{% component "user_card"
    username=my_user.username
    is_active=(my_user.status == 'active')
    is_admin=(my_user.role == 'admin')
    score=(my_user.points + bonus_points)
/ %}
Using Python expressions for multiple attributes with comparisons and arithmetic

johndoe

Status: active

Score: 175

Admin

List and dictionary operations

{% component "button"
    text=(items[0].title if items else 'No Items')
    disabled=(items_len == 0)
    variant=(config.get('button_style', 'primary'))
/ %}
Python expressions work with lists, dicts, and other data structures

Comparison with Alternatives

Without Python expressions (verbose)

You would need to compute values in get_template_data():

def get_template_data(self, args, kwargs, slots, context):
    return {
        "disabled": not kwargs["editable"],
        "variant": "danger" if kwargs["my_user"].is_admin else "primary",
    }

With Python expressions (concise)

Evaluate directly in the template:

{% component "button"
    disabled=(not editable)
    variant=(my_user.is_admin and 'danger' or 'primary')
/ %}

Best Practices