How to get the string in AnQiCMS template?

Calendar 👁️ 73

In AnQiCMS template development, text and strings are the foundation for building website content.No matter whether it is to display article titles, website names, or handle user input, being able to flexibly and efficiently obtain and operate strings is a skill that template developers must master.AnQiCMS is a powerful template engine based on Go language, providing rich tags and filters, making string retrieval and processing intuitive and practical.

Core mechanism: Understand the string retrieval method of AnQiCMS template

In AnQiCMS template, the most direct way to obtain a string is through variable reference. Just like in a common programming language, you can access{{ 变量名 }}The value of a variable is output in the form. When a variable is a struct or object, its properties can be accessed using a dot ("). For example"}.) to access its properties. For example{{ archive.Title }}The title of the current document will be output.

To obtain strings of a specific type more accurately, AnQiCMS provides various template tags:

  • To obtain the details of the content stringFor example, on the article detail page, you may need to retrieve the article title, content, keywords, or custom fields.{% archiveDetail %}Tags provide this capability. BynameSpecify the field name to be retrieved, such as{% archiveDetail with name="Title" %}Can retrieve the article title,{% archiveDetail with name="Description" %}Get the article description. For document content, you can use{% archiveDetail with name="Content" %}. Similarly,{% categoryDetail %}Used to get the category detail string,{% pageDetail %}Used for single page,{% tagDetail %}Used for label details.
  • String to get global site information.: Website name, copyright information, contact information, etc. are usually global configurations.{% system %}Tags can obtain strings from system settings, for example{% system with name="SiteName" %}Get the website name.{% contact %}Tags are specifically used to obtain contact information, for example{% contact with name="Cellphone" %}Get the contact phone number. If you have customized parameters in the background, you can also get these labels by simply settingnamethe parameter name you define.
  • Get string in list or loopWhen you need to display a list of articles, categories, navigation, etc.{% archiveList %}/{% categoryList %}/{% navList %}And tags. These tags are usually with{% for %}Use loops in combination. Inside the loop body, the string properties of each list item (such asitem) can be accessed directly using the dot notation, such as{{ item.Title }}/{{ item.Description }}.
  • Define a temporary string variableSometimes you may need to define temporary string variables in the template for reuse or complex operations.{% set new_var = "这是我的自定义字符串" %}and{% with title="文章标题" %}Both of these methods can help you create and use string variables in the template.

The powerhouse of string manipulation: built-in filters

After obtaining a string, it often needs to be further processed, such as formatting, truncation, cleaning, or escaping. AnQiCMS template engine built-in a large number of practical filters, which through|Connecting symbols with variables, it can be used in a chain, greatly enhancing the flexibility of string processing.

  • Formatting and conversion:
    • Case conversion:|upperConvert string to uppercase,|lowerConvert to lowercase,|capfirstCapitalize the first letter,|titleCapitalize the first letter of each word, which is very practical in text display processing.
    • General formatting:|stringformat:"%s"The various types of values can be formatted as strings and support fine control with Go-style placeholders.
    • Type conversion:|integerand|floatTry converting a string to an integer or float, which is very useful when dealing with strings containing numbers.
  • Cut and paste:
    • Cut a specified part:|slice:"start:end"Can extract a specified segment of a string or array, for example{{ "abcdefg"|slice:"1:4" }}You will get “bcd”.”
    • Truncate display:|truncatechars:长度Truncate the string by character length and add an ellipsis (...)|truncatewords:长度Truncate by word count. If the string contains HTML, you can use|truncatechars_htmland|truncatewords_htmlThey will try to maintain the integrity of the HTML structure during truncation.
    • String concatenation and splitting:|join:"分隔符"Combine array elements into a string, and|split:"分隔符"Then you can split the string into an array by the separator.|make_listand|fieldsAlso split strings into character or word arrays quickly
  • Clean and replace:
    • Delete characters:|trimYou can remove spaces or specified characters from the beginning and end of a string,|trimLeftand|trimRightwhich handles the left and right sides separately.|cut:"字符"You can remove all occurrences of a specific character from a string.
    • Replace content:|replace:"旧词,新词"You can replace the old content in a string with new content, which is very convenient when making batch text modifications or handling specific keywords.
  • Security and coding:
    • HTML safe output:AnQiCMS template defaults to escaping output HTML tags to prevent XSS attacks. If you are sure that a certain string content is safe HTML code and you want it to be parsed normally by the browser, you can use|safeFilter. For example, article content usually contains HTML, which needs{{ archive.Content|safe }}. Conversely,|escape(or its alias|e) will force HTML escaping.
    • URL encoding:|urlencodeand|iriencodeUsed for URL parameter encoding to ensure the validity and security of the URL.
    • Converts newline characters to HTML.:|linebreaksand|linebreaksbrCan convert newline characters in text to.<p>tags or<br>Label, suitable for formatting plain text content as a web paragraph.
  • Other practical functions:
    • Default value:|default:"默认文本"Provide a default string when the variable is empty.
    • Statistical information:|lengthGet the length of a string or array,|wordcountCount the number of words in a string,|count:"关键词"Count the frequency of keywords.
    • Debugging tool: When you are unsure about the structure or value of a variable,|dumpThe filter can print out the detailed information of a variable (including type and value), which is very useful during template debugging.

Practical suggestions and techniques.

  1. Define the goalBefore obtaining a string, determine what information you need (whether it's the article title or the website name) and then choose the most suitable tag.
  2. Make good use of the dot operator.: For the objects already obtained, prefer to useitem.PropertyNameto access string properties, which is usually more concise and efficient than repeatedly calling labels.
  3. chaining filters: Multiple filters can be connected in series like a pipeline, with the output of one filter being the input to the next. For example,{{ item.Title|lower|truncatechars:20 }}convert to lowercase first and then truncate.
  4. Use with caution.|safe:|safeCan directly output HTML, but if the content source is not trustworthy, it may introduce security risks. Only use it when you fully trust the content source.
  5. Debugging skillsIf the string output does not meet expectations, try adding to the variable|dumpFilter to view the original structure and values, which will help you locate the problem. For example{{ someVariable|dump }}.

The AnQiCMS mechanism for obtaining and processing strings in templates is powerful and flexible. By mastering the usage of various tags and filters, you can easily build beautiful and functional website content.


Frequently Asked Questions (FAQ)

Q1: How to get the current page title in a web page and automatically append the site name? A1:You can usetdkLabel and combine `siteName

Related articles

What is the type of the string array after splitting the `fields` filter in AnQiCMS template?

In AnQiCMS template development, we often need to process text content, such as splitting a string of keywords, tags, or descriptions into independent entries for list display or further operations.At this time, the `fields` filter has become a very practical tool.It can efficiently complete the splitting of strings, but many users may be curious about the data types of the split strings after the `fields` filter is applied.Understand the working mechanism of the `fields` filter

2025-11-08

How to split a long string into an array of strings in AnQiCMS template?

During AnQiCMS template development, we often encounter situations where we need to flexibly handle data, one common requirement being to split a long string containing multiple pieces of information into an independent string array using a specific delimiter (such as a space), so as to facilitate loop display or further operations.AnQiCMS's template engine provides a concise and efficient filter (Filter) function, which can easily achieve this goal.### Understand `split`

2025-11-08

How to use the `autoescape` tag to control the automatic escaping of HTML content in AnQiCMS templates?

It is crucial to understand and effectively control the escaping behavior of HTML content during AnQiCMS template development.This not only concerns the correct display of page content, but also directly affects the security of the website, especially in preventing cross-site scripting (XSS) attacks.AnQiCMS's template system provides a flexible mechanism to manage this, with the `autoescape` tag playing a core role.

2025-11-08

escape` filter and `e` filter in AnQiCMS template are they functionally the same?

During the development of AnQiCMS templates, the security of data output is a focus we need to pay attention to.Frequently encounter issues about `escape` filter and `e` filter, many users are curious about whether there are differences in their functions.

2025-11-08

How to display the title and content of articles in AnQiCMS templates?

Manage website content in AnQiCMS, the ultimate goal is to be able to present this content to visitors in an elegant and efficient manner.For the most common content type of articles, how to accurately display the title and body in front-end templates is a basic skill that every website operator needs to master.AnQiCMS powerful template function, providing us with a flexible and intuitive implementation method.### Core: Get to know the `archiveDetail` tag AnQiCMS's template system is designed to be very user-friendly

2025-11-08

How to implement personalized display of front-end content in AnQiCMS?

In today's era of content overload on the internet, how to make a website stand out and provide a unique and valuable experience to visitors has become crucial.The personalized display of content is an important means to enhance user stickiness, conversion rate, and brand image.AnQiCMS as an efficient and customizable content management system provides many features to help us easily achieve this goal.The flexible construction of content models: the foundation of personalized display The first step in personalized display is to make our content inherently personalized.The flexible content model feature of AnQiCMS

2025-11-08

What template file extensions and storage locations does AnQiCMS support?

AnQiCMS as a flexible and efficient content management system provides powerful template customization capabilities.It is crucial to make full use of this advantage of AnQiCMS and understand the suffix and storage location of its template files.This can not only help you design websites more efficiently, but also locate and solve problems faster when encountering them.First, AnQiCMS template files use the `.html` suffix.This means that all template files you create or edit should be saved in HTML format. These`

2025-11-08

How to use AnQiCMS built-in tags to control content display logic?

In AnQiCMS, the built-in tag system is the core tool you use to control the logic of displaying website content.It provides a powerful and flexible syntax that allows you to control the acquisition, filtering, sorting, formatting, and final layout of content in template files without writing complex backend code.This system is similar to the Django template engine syntax, easy to use, and can help you convert technical details into intuitive display effects.

2025-11-08