In AnQiCMS template development, we often need to perform simple addition operations or string concatenation.addThe filter is born for this.It is very convenient to use, capable of intelligently handling the addition of numbers and concatenation of strings.If you give it two numbers, it will perform mathematical addition; if you give it two strings, it will concatenate them.Even if it is a mix of numbers and strings, AnQiCMS will try to perform a reasonable conversion and output the result.
For example, add numbers:
{{ 5|add:2 }}
{# 显示结果: 7 #}
Or, perform string concatenation:
{{ "安企"|add:"CMS" }}
{# 显示结果: 安企CMS #}
Then, when one of the variables is:nothingornil(This usually represents that the variable has not been assigned or is empty in the template context) when,addThe behavior of the filter is particularly critical. Many users may worry that this could lead to template rendering errors or unexpected results.
AnQiCMSaddThe filter in processingnothingorniltakes a very practical strategy when encountering:It will intelligently ignore thatnothingorniloperand, processing only the valid operands.
This means, if you try to add a number with anothingvalue, the final result will be that valid number itself, not an error or zero. For example:
{% set my_optional_number = nothing %}
{{ 10|add:my_optional_number }}
{# 显示结果: 10 #}
Similarly,nilThis is the first operand, and the result is also the same:
{{ nil|add:20 }}
{# 显示结果: 20 #}
The behavior is similar for string concatenation:
{{ "开始"|add:nil }}
{# 显示结果: 开始 #}
AnQiCMSaddThe filter tries to perform type conversion on the operands internally. When encounteringnothingornilWhen, it cannot successfully convert it to a usable type for addition or concatenation (such as a number or a non-empty string), it will choose to ignore this invalid operand and only process the valid operands. This design ensures that the template can render as normally as possible even when the data is incomplete, avoiding individual