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