In AnQiCMS website operation, maintaining the standardization of product units and currency symbols is a key factor in enhancing user experience and professionalism.We often need to unify the format of data from different sources and different input habits.replaceCan the filter be effectively used to achieve this goal? The answer is affirmative, by巧妙运用replaceFilter, we can standardize these display contents flexibly at the template level without modifying the data in the original database.

UnderstandingreplaceThe working principle of the filter

AnQiCMS uses syntax similar to Django template engine, which includes a variety of filters (filters) to handle data display on the front end.replaceThe filter is one of the very practical tools, which allows us to replace a specific "old word

{{ obj|replace:"旧词,新词" }}

Here are theobjIt is a variable that needs to be processed, such as product price or unit field, and旧词and新词separated by commas,. It is noted that,replacethe filter performs precise string matching and replacement.

Actual application scenario one: Standardized product units

Our product content model has a "weightreplaceThe filter can be used.

For example, we hope to display all “g” as “gram”:

{{ product.Weight|replace:"g, 克" }}

If the original data contains “kilogram”, we can also perform multiple replacements, or first unify it to a middle format:

{# 假设原始数据是 "1公斤" 或 "500g" #}
{{ product.Weight|replace:"公斤,000克"|replace:"g,克" }}
{# "1公斤" -> "1000克";"500g" -> "500克" #}

Through this method, we can automatically convert various irregular unit representations into the uniform format we expect when rendering to the page, greatly enhancing the standardization of the content.

Actual application scenario two: Uniform currency symbol display

When displaying product prices, the standardization of currency symbols is also important.For example, the backend may store "USD 100

UtilizereplaceFilter, we can operate like this:

{# 将 "USD" 替换为 "$" #}
{{ product.Price|replace:"USD, $" }}

{# 将 "¥" 替换为 "¥"(如果输入的是全角或不标准符号) #}
{{ product.Price|replace:"¥, ¥" }}

{# 处理“欧元”的替换 #}
{{ product.Price|replace:"欧元, €" }}

It should be noted that if the price field is a pure number and we want to add a currency symbol in front of it,replaceThe filter itself is not suitable for direct addition. It is better at replacing existing strings. If faced with this situation, we may need to first format the number as a string (for example, usingstringformatorfloatformatFilter, then perform the replacement operation:

{# 假设 product.RawPrice 是一个数字,我们希望显示为 "$100.00" #}
{{ product.RawPrice|floatformat:2|add:"^"|replace:"^, $" }}
{# 这里巧妙地利用 add 添加一个特殊字符,再替换为 $。不过更推荐直接字符串拼接。 #}
{# 更直接的拼接方式(非replace功能): "$"|add:product.RawPrice|floatformat:2 #}
{# 但如果原始价格是 "100 USD",要换成 "$100": #}
{{ product.PriceWithCurrency|replace:"USD, $" }}

Consideration for multilingual support

AnQiCMS provides powerful multilingual