During the process of building a website with AnQiCMS, we often need to display various data on the front-end page, which often comes with different statuses.For example, whether an article is published or a draft, a product is on sale or off the shelf, or whether a user is active.How to clearly and intuitively present these states to users while maintaining the conciseness and readability of the template code is a common issue that content operators and template developers often ponder over.yesnoFilter, it can help us solve this problem gracefully.
yesnoFilter: makes state expression more intuitive.
yesnoThe filter is a built-in tool provided by AnQiCMS template engine, whose core function is to output different text based on the value of a variable (usually a boolean value or data that can be interpreted as a boolean). It can converttrue/falseandnilThis three states are mapped to the descriptive text we specify, making the status information of the data clear at a glance.
By default,yesnothe filter willtrueThe value is converted to “yes”,falseThe value is converted to “no”, andnil或空值则转换为“maybe”。This default behavior is sufficient in many scenarios, but its real strength lies in its high degree of customization. We can define any text we want for these three states according to our actual needs.
Why chooseyesnoFilter?
UseyesnoFilter rather than traditionalif-elseLogic to display simple boolean states, several significant advantages include:
FirstlySimplicity and readability of codeImagine that, if you need to write code for each state judgment{% if condition %}显示文字{% else %}显示另外的文字{% endif %}, the code would become verbose.{{ item.IsActive|yesno:"活跃,冻结,未知" }}This writing, not only can be done in one line of code, but the semantics are also clearer, making it easy to understand the corresponding relationship between the variable and the displayed text at a glance.
ThenCentralized management of output text.yesnoFilter, we can define the text corresponding to the state in the filter parameters, rather than scattered in multipleifBranch inside. When adjusting the display text, it only needs to be modified in one place, which greatly reduces maintenance costs, especially in a multilingual environment, this advantage is more obvious.
Finally, it provides aelegant way to handle missing (nil) data. In practical development, data fields occasionally appear to have empty values or not set.yesnoThe default 'maybe' output of the filter, or the custom 'status unknown' and other texts, can provide friendly prompts when data is incomplete, rather than allowing the page to display blank or error messages.
yesnoFilter combination practice with data list
Now, let's look at a specific example to demonstrateyesnoHow does the filter combine with AnQiCMS's data list to display the specific status of each data item.
Suppose our article (or any document model) has a custom field namedIsRecommended(whether recommended),