In the daily operation of the website, we often need to display date and time information in a user-friendly manner.It is particularly important to be able to output date and time formats that match local customs when facing users from different regions, which is what we commonly refer to as 'internationalized format output'.Today, let's talk about a commonly used filter in AnQiCMS (AnQiCMS)stringformatLook at how it handles date and time objects, whether it supports this customized internationalization format output.

Get to know in-depthstringformatFilter

First, let's reviewstringformatThe core function of the filter. According to the document description of AnQi CMS,stringformatThe filter is mainly used to format any value such as numbers, strings, arrays, etc. into a string according to the specified format. Its usage is similar to that in Go language.fmt.Sprintf()Functions allow us to flexibly combine and format different types of data. For example, we can use it to control the number of decimal places of floating-point numbers, or embed numbers into a piece of text:

{{ 3.141592653|stringformat:"%.2f" }}  {# 输出 3.14 #}
{{ 888|stringformat:"库存数量:%d" }}  {# 输出 库存数量:888 #}

It is not difficult to find through these examples,stringformatThe filter performs well in general data formatting. However, when it comes to date-time objects, the situation is different.In the Anqi CMS template system, the datetime object (whether it is a Unix timestamp or Go language nativetime.TimeFormatting of (type) is usually handled by special tags or filters, rather thanstringformat.stringformatThe design intention is more for the string conversion of general data types, it itself does not contain the specific logic required for date and time formatting, such as parsing the components of the date (year, month, day, hour, minute, second) and outputting according to a specific layout string.

Special tool for date and time formatting in AnQiCMS

In AnQiCMS, we mainly rely on two powerful tools for processing and outputting date and time formats:stampToDateTags anddatefilter.

  • stampToDateTagThis tag is specifically used to format 10-digit Unix timestamps.It requires a timestamp and a time layout string that conforms to the Go language standard.For example, if you have aCreatedTimeThe field stores the timestamp:

    {# 格式化为 年-月-日 #}
    {{ stampToDate(item.CreatedTime, "2006-01-02") }} {# 例如输出 2023-10-27 #}
    
    {# 格式化为 年-月-日 时:分:秒 #}
    {{ stampToDate(item.CreatedTime, "2006-01-02 15:04:05") }} {# 例如输出 2023-10-27 10:30:00 #}
    

    Here"2006-01-02"It is not a literal date, but a specific layout (Layout) template defined in the Go language, representing the format of "year-month-day".

  • dateFilter: withstampToDatesimilar,dateThe filter is also used for date and time formatting, but it expects antime.Timetype of object (not a timestamp). Its usage is similar tostampToDateAlmost identical, using the Go language time layout string:

    {# 假设 someTimeVariable 是一个 time.Time 对象 #}
    {{ someTimeVariable|date:"Jan 02, 2006" }} {# 例如输出 Oct 27, 2023 #}
    

whether it isstampToDateOrdateFilters, they all provide powerful custom format output capabilities, but this "customization" is based on the preset layout strings of the Go language, that is, you must explicitly specify what "year" is represented by, what "month" is represented by, and so on.

Consideration for internationalized format output

Now let's return to the core issue of 'Internationalized Format Output'. Anqi CMS provides multilingual support at the content level, you can set the default language package of the website, even throughlanguagesLabel to retrieve links to different language sites and go throughtrLabel to translate text in the translation template. However, as for date and time formatting,stampToDateanddateThe filter does not have a built-in function to automatically identify the current user's language environment and output the corresponding date format.

This means, if you want to implement date format output for different language environments (such as Chinese users seeing2023年10月27日, English users seeingOctober 27, 2023, German users seeing27. Oktober 2023), relying solely onstampToDateordateThe label cannot be directly passed a generic format. The layout string you passed in"2006年01月02日"Always output the format with Chinese characters 'year', 'month', 'day', regardless of the user's current language environment.

The idea of implementing internationalized date format.

To implement the internationalization of date and time formats, we usually need to combine with other functions of Anqi CMS, and judge and process through template logic:

  1. Get the current language environment: You can control it through{% system with name='Language' %}Tag to obtain the language code of the current site (for examplezh-CN,en-US,deetc.).

  2. Conditional judgment to apply different layouts: In the template, use the obtained language code to{% if %}Logic to select different Go language date layout strings, pass tostampToDateordate.

    {% set currentLang = system.Language %} {# 假设system.Language能获取到当前语言代码,具体字段需查阅系统标签 #}
    {% set myTimestamp = archive.CreatedTime %} {# 假设从archive获取时间戳 #}
    
    {% if currentLang == "zh-CN" %}
        {{ stampToDate(myTimestamp, "2006年01月02日") }}
    {% elif currentLang == "en-US" %}
        {{ stampToDate(myTimestamp, "January 02, 2006") }}
    {% elif currentLang == "de" %}
        {{ stampToDate(myTimestamp, "02. Januar 2006") }}
    {% else %}
        {# 默认或备用格式 #}
        {{ stampToDate(myTimestamp, "2006-01-02") }}
    {% endif %}
    

This method requires some manual configuration, but it is an effective way to achieve date and time internationalization format output under the current functional system of Anqi CMS.

Summary

stringformatThe filter in Anq CMS is a general-purpose string formatting tool that does not directly support the formatting of date-time objects and does not have the function of automatically internationalizing date formats. For the processing of date-time objects, we should use specializedstampToDateLabel (for timestamp) ordateFilter (fortime.TimeAn object is passed, and the Go language standard time format string is used.To implement the internationalization of date and time formats, it is necessary to manually apply different date layout strings in the template based on the language environment.


Frequently Asked Questions (FAQ)

1.stringformatFilters andstampToDateWhat is the core difference between labels?

stringformatThe filter is a universal string formatting tool that is suitable for various data types such as numbers, strings, arrays, and usesfmt.Sprintf()style-based format definitions. AndstampToDateThe label is specifically designed for Unix timestamps, used to convert them into a datetime string with a specific format, following the Go language's date layout rules. Simply put,stringformatDon't understand dates,stampToDateBut you are an expert in date handling.

2. Can Anqi CMS automatically switch the date format according to the visitor's browser language?

The AnQiCMS built-in date-time formatting tags (such asstampToDateanddateCurrently, it does not directly support adjusting the date format according to the visitor's browser language.They depend on the hard-coded Go language layout strings in the template.To implement this dynamic switch, you need to write conditional logic in the template to obtain the current page or the language environment set by the user (for example, throughsystemtags), then manually select and apply the corresponding date format layout according to the language code.

3. The time formatting layout (Layout) string in Go language is not very intuitive, is there an easier way to remember it?

The time layout of Go language is indeed quite special, it does not use commonYYYY-MM-DDsuch placeholders, but uses a fixed reference time2006年01月02日 15时04分05秒 -0700 MSTDefine the layout. Although it may seem inconvenient at first, remember the meaning of each number and symbol in this reference time (for example2006represents the year,