In AnQiCMS template development, we often encounter the need to handle string or array content, such as displaying article summaries, limiting the number of image lists, or extracting specific information from a long text.The AnQi CMS is developed based on Go language, its template engine supports syntax similar to Django and Blade, and provides a rich set of filters to help us efficiently complete the content extraction and display requirements.
Let's take a look at how to flexibly extract a specified part of a string or array for display in the AnQiCMS template.
Core method:sliceFilter implementation for accurate extraction
When we need to perform precise segment extraction of strings or arrays (usually slices in Go language),sliceThe filter is our preferred tool. It allows us to specify a start and end position to get a subset of the content.
Basic usage
sliceThe syntax of the filter is very intuitive:{{ obj|slice:"start:end" }}.
startThe parameter is the starting index (including this position).endThe parameter is the ending index (not including this position).- Indexes start counting from 0.
Flexible extraction method
sliceThe filter is very flexible, we can omit as neededstartorend:
{{ obj|slice:":end" }}: From the beginning toendbefore.{{ obj|slice:"start:" }}: fromstartPosition to the end.{{ obj|slice:"start:end" }}: Cut fromstarttoendThe part between.- Additionally, it also supports negative indices, such as.
{{ obj|slice:"-3:" }}This indicates starting from the third element from the end to the end, which is very convenient in some cases.
Actual application example
Assuming we are developing a news list, we need to display the first few words of the article title, or show the first three images on the product detail page.
Extracting a string (such as a part of the article title):If
archive.TitleIs “AnQiCMS template development and content operation guide”, we want to display only the first 10 characters:<p>标题前10字:{{ archive.Title|slice:":10" }}</p>Output may be: 'AnQiCMS template development and content operation'
Truncate array (such as the first few pictures in the picture list):Assume
archive.ImagesIs an array containing multiple image URLs["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"]We only want to display the first two pictures:{% set firstTwoImages = archive.Images|slice:":2" %} {% for img in firstTwoImages %} <img src="{{ img }}" alt="产品图片"> {% endfor %}Here, we first use:
setThe tag will assign the captured result to:firstTwoImagesThe variable, and then output it in a loop.Combine negative index to截取数组:If we need to display the last two elements of the array:
{% set lastTwoImages = archive.Images|slice:"-2:" %} {% for img in lastTwoImages %} <img src="{{ img }}" alt="产品图片"> {% endfor %}
Other useful methods: slicing and processing
exceptsliceFilters provide precise truncation, in addition, AnQiCMS also provides some other filters that can help us truncate, process, and display string or array content in different ways.
firstandlastFilter: Get the first or last elementWhen you only need to get the first or last element of a string or array,firstandlastthe filter is very convenient.{{ obj|first }}Get the first character or the first element of an array.{{ obj|last }}Get the last character or the last element of an array. For example, get the first tag in the list of article tags:
{% tagList tags with itemId=archive.Id limit="1" %} {% if tags %} <p>第一个标签:{{ tags|first.Title }}</p> {% endif %} {% endtagList %}truncatecharsandtruncatewordsFilter: Limit length and add ellipsisThese filters are mainly used to control the display length of text and add ellipsis when it exceeds the specified length (...They are very suitable for displaying in article summaries or introductions.{{ obj|truncatechars:number }}: Truncated by character count, including ellipses. Words may be cut off.{{ obj|truncatechars_html:number }}: Safely extract strings containing HTML tags without destroying the HTML structure.{{ obj|truncatewords:number }}: Truncate by word count, including ellipses, without breaking words.{{ obj|truncatewords_html:number }}: Safely truncate a string containing HTML tags, counting by words. For example, display the first 50 characters of the article summary and ensure that the HTML tags are not destroyed:
<p>简介摘要:{{ archive.Description|truncatechars_html:50|safe }}</p>Note
|safeThe use, it indicates that this content is safe HTML and does not require escaping.splitandjoinFilter: Interconversion between strings and arrays.When processing some strings stored with a specific delimiter (such as comma-separated keywords),splitandjoinThe filter will be very useful.{{ obj|split:"分隔符" }}: Split the string into an array according to the specified delimiter.{{ arr|join:"分隔符" }}Concatenate array elements into a string with a specified separator. Assumearchive.KeywordsIs a comma-separated string “AnQiCMS,GoLang,CMS system”, we want to get the first keyword:
{% set keywordsArray = archive.Keywords|split:"," %} <p>第一个关键词:{{ keywordsArray|first }}</p>Or, you can also use it first:
splitConvert to an array and then usesliceGet a part, thenjoinConvert back to a string:{% set topTwoKeywords = archive.Keywords|split:","|slice:":2"|join:" & " %} <p>主要关键词:{{ topTwoKeywords }}</p>The output may be: ”AnQiCMS & GoLang”
lengthFilter: get the lengthAlthoughlengthThe filter itself is not used for truncation, but it is often used in truncation scenarios to judge the content length, thereby deciding whether to truncate or display specific content.{{ obj|length }}Get the length of a string, array, or key-value pair. For example, only display the title if it exceeds 20 characters.
{% if archive.Title|length > 20 %} <p>短标题:{{ archive.Title|slice:":20" }}...</p> {% else %} <p>完整标题:{{ archive.Title }}</p> {% endif %}
How to choose the appropriate method?
Choose which method depends on your specific needs:
- Need to control the range of truncation (from which index to which index) exactly: Use.
slicefilter. - Only need to get the first or last element: Use.
first