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 and can intelligently handle 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 when numbers and strings are mixed, AnQiCMS will try to perform a reasonable conversion and output the result.

For example, adding numbers:

{{ 5|add:2 }}
{# 显示结果: 7 #}

Or, perform string concatenation:

{{ "安企"|add:"CMS" }}
{# 显示结果: 安企CMS #}

Then, when one of the variables is:nothingornil(In the context of a template, it usually represents that the variable has not been assigned or is empty)addThe behavior of the filter is particularly critical. Many users may worry that this could lead to template rendering errors or unexpected results.

AnQiCMS'addThe filter is processingnothingornilWhen encountering a situation, it will adopt a very practical strategy:It will intelligently ignore thatnothingornilIt will only process the valid operands.

This means that if you try to add a number with anothingWhen added, the result will be the valid number itself, not an error or zero. For example:

{% set my_optional_number = nothing %}
{{ 10|add:my_optional_number }}
{# 显示结果: 10 #}

Similarly, ifnilis the first operand, the result will be the same:

{{ nil|add:20 }}
{# 显示结果: 20 #}

For string concatenation, the behavior is similar:

{{ "开始"|add:nil }}
{# 显示结果: 开始 #}

AnQiCMS'addThe filter tries to convert the operands internally. When encounteringnothingornilWhen, it fails to convert it into a valid type that can be used for addition or concatenation (such as a number or a non-empty string), it will ignore the 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 single