Add a as_type= argument for {% definevar %} for casting to types.
Review Request #14698 — Created Nov. 18, 2025 and updated
{% definevar %}can now store a value as a boolean or integer through
theas_type=argument. By default, this stored as a string
(equivalent tostr).When passing
as_type=bool, atrue(lowercased) or1will
result in a storedTrue. Anything else will beFalse.When passing
as_type=int, the value will be converted to an integer.
If the value can't be parsed as an integer, aTemplateSyntaxErrorwill
be raised.There's also an optimization around the options. We now convert to a
setso we don't repeatedly iterate through the list for each option.
Unit tests pass.
Made use of this in some in-progress code in Review Board for setting
options.
| Summary | ID |
|---|---|
| b07678ceb1eb5292b075300623226a4663108dc6 |
| Description | From | Last Updated |
|---|---|---|
|
The end sounds a bit weird, maybe say "... before use." |
|
|
|
Shouldn't here and the "Version Added"s below all be "Version Changed" instead? |
|
|
|
Shouldn't the result of this always be str, not Any? Given that this is essentially a parse step, it would … |
|
|
|
Perhaps we should raise TemplateSyntaxError if 'spaceless', 'strip', or 'unsafe' are provided but we're casting to bool or int? |
|
|
|
You're stripping twice here. |
|
|
|
Can we add tests for "1", "TRUE", "0", "false", as well as a few including whitespace (" true", " 1 … |
|
|
|
Can we add tests with whitespace, 0, and negative numbers? |
|
-
-
Shouldn't the result of this always be
str, notAny?Given that this is essentially a parse step, it would be nice to assign the result after the parse to a separate variable which is explicitly typed as
str | SafeString | int | boolinstead of reassigning toresult -
Perhaps we should raise
TemplateSyntaxErrorif 'spaceless', 'strip', or 'unsafe' are provided but we're casting to bool or int? -
-
Can we add tests for "1", "TRUE", "0", "false", as well as a few including whitespace (" true", " 1 ")?
-