if
and else
Template Filters
The if
and else
template filters are provided to enable conditional attribute values with the ...
attribute template tag:
The if
and else
template filters are automatically available in your components' templates, in other templates be sure to {% load tetra %}
.
if
Filter
When the value of the right hand argument evaluates to True
it returns the value of its left hand argument. When the value of the right hand argument evaluates to False
it returns an empty string ""
(a falsy value).
So when setting a class:
if my_var=True
you will generate this HTML:
if it's False
then you will receive this:
else
Filter
When the value of the left hand argument evaluates to True
it returns the value of its left hand argument. When the value of the left hand argument evaluates to False
(such as an empty string ""
) it returns the value of its right hand argument.
So with this:
If context_var="Some 'Truthy' String"
then you will generate this HTML:
if it's False
then you will receive this:
Chaining
if
and else
can be chained together, so with this:
If variable_name="A 'Truthy' Value"
then you will generate this HTML:
if it's False
then you will receive this:
It is possible to further chain the filters such as:
The @v
tag
When variables are displayed in components, a common pattern is that a string should reflect a variable name "live", as you type. While a normal Django variable {{ title }}
will get only updated after the next rendering of the component (e.g. after you call a backend method), Tetra provides a convenience way to render a variable instantly in the frontend using Alpine.js: {% @v title %}
.
<div class="card">
<div class="card-title">Current title: {{ title }} - New title: {% @v title %}</div>
<div class="card-body">
<input type="text" x-model="title">
</div>
<div class="card-footer">The title is: {% @v "title" %}</div> {# with quotes #}
</div>
<span x-text="title"></span>
and let Alpine.js do the rest.