Day 11 of 100 Days of Django: Django Template Language Part II
Hi🙋♂️ Devs, Let’s see List of Filters and Conditional Statements in (DTL)🤔.
List of Filters🔗
- capfirst → It capitalizes the first character of the value.If the first character is not a letter, this filter has no effect🧢.
Example: {{value|capfirst}}
- default → If value evaluates to False, use the given default. Otherwise uses that value.
Example: {{value|default:”other value”}}
If value is “” (the empty string) the output will be “other value’
- length → It returns the length of the value.This works for both strings and lists. The filter returns 0 for an undefined variable.
Example: {{value|length}}
- lower/upper → It converts a string into all lowercase/uppercase💼.
Example: {{value|lower\upper}}
- slice → It returns a slice of the list. Uses the syntax as Python🐍 list slicing.
Example: {{some _list|slice: “:2”}}
truncatechars/truncatewords: It truncate words/chars after certain number of specified chars or words.
Example:{{some_string|truncatewords/truncatecchars:2}}
Link for More Tags😀:
Conditional Statements
if Tag:
{% if %} tag evaluates a variable and if that variable is true (i.e exists is not empty and is not a false boolean value.)
Syntax:
{% if variable %}
some code
{% endif %}
We can (and, or, not,==,in, not in, etc ) with it
{% if variable1 and variable2 %}
some code
{% endif %}
{% if variable1 or variable2 %}
some code
{% endif %}
{% if not variable1 %}
some code
{% endif %}
We can also apply filter on the variable before comparing it.
Syntax:
{% if variable1|length <=2 and variable2 %}
some code
{% endif %}
In the Next Article we are going to see Dot Lookup and For Loop👨💻, So stay tuned.
Thanks for Following and Claps😋
Link to Day 12