Drive time: Anqi CMS inarchiveListLoopstampToDateThe way of date formatting

In the world of content management, the publication time, update time, and other date information of website content are not only key elements providing critical context to readers, but also an important manifestation of the professionalism and user experience of the website.For AnQiCMS, a Go language-based, high-efficiency and flexible enterprise-level content management system, how to elegantly present these original timestamps stored in the database to the user is a common and core requirement in template development.Today, we will delve deeply into AnQiCMSarchiveListthe loop,stampToDateTags ensure that the creation time of each document is precise and beautifully formatted.

UnderstandingarchiveListWith the original timestamp

Firstly, we know that Anqi CMS passes througharchiveListThe tag can easily retrieve a series of document (article, product, etc.) data from the background. This tag is powerful, and it can filter and sort content according to category ID, module ID, recommendation attributes, or even search keywords, ultimately presenting a collection of multipleitemThe list of objects is presented in the template for us to iterate over.

In theseitemobjects,item.CreatedTimeanditem.UpdatedTimeThis field usually stores a Unix timestamp—a sequence of integers representing the number of seconds since 00:00:00 UTC (Coordinated Universal Time) on January 1, 1970.This storage method is very friendly to database and program processing, but directly displaying this string of numbers on the website front-end clearly does not meet the reading habits of users and does not seem professional.This brings up the need to translate timestamps.

stampToDate:The translator of timestamps

To solve the problem of timestamp display, Anqi CMS provided a very practical template tag -stampToDate. Its core function is to convert the original timestamp into the date or time string we want. The usage of this tag is intuitive and flexible:{{stampToDate(时间戳, "格式")}}.

The most critical part is the second parameter - 'format'. Unlike many programming languages, Go language uses a unique 'reference time' mechanism when formatting time, rather than relying on abstract letter codes such asY-m-d)。Safe CMS'sstampToDateThe tag has continued this feature. The formatting string needs to be based on the fixed reference time of the Go language:2006年01月02日 15时04分05秒This means, if you want to display the year, write '2006'; if you want to display the month, write '01'; if you want to display the hour, write '15', and so on.

For example, if we need to format a timestamp as "2023-10-27", then the format string is"2006-01-02"If you want to display the date and time to the minute, for example, “October 27, 2023, 10:30”, the format string will be"2006年01月02日 15:04"This design may look peculiar at first glance, but once mastered, one can appreciate its precision and powerful control.

stampToDateInarchiveListHow to ensure correct formatting in a loop

Now, let's takearchiveListandstampToDateCombine it and see how it ensures that each document's creation time is formatted correctly in practice.

When we use in the templatearchiveListGet the list of documents and loop through them, like this:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <article>
        <h2><a href="{{item.Link}}">{{item.Title}}</a></h2>
        <p>
            发布于: {{stampToDate(item.CreatedTime, "2006年01月02日 15:04")}}
            <span class="views">阅读量: {{item.Views}}</span>
        </p>
        <div class="description">{{item.Description}}</div>
    </article>
    {% empty %}
    <p>暂时没有可供显示的文档。</p>
    {% endfor %}
{% endarchiveList %}

The key point is hereforEach iteration of the loop. When the loop processesarchivesover each element in the listitemthen,stampToDatethe function is called independently and receives the currentitemofCreatedTimeas its first parameter.

Specifically, eachfor item in archiveswhen executed:

  1. The system will take the original timestamp value from theitemobjectCreatedTimefield of the current iteration.
  2. This original timestamp value will be passed as thestampToDatefirst parameter of the function.
  3. stampToDateThe function will use the second parameter (for example"2006年01月02日 15:04")Define the format to convert the current timestamp.
  4. The converted date-time string will replace the{{stampToDate(...)}}part in the template, and be displayed on the page.

This process is for each one in the loopitemexecuted independently, so no matter how many documents are in the list,stampToDateit can ensure that each document'sCreatedTimeThis is formatted correctly and consistently. This individual processing mechanism ensures a high correspondence and accuracy of time and formatting, greatly simplifying the complexity of front-end date display.

The practical significance and operational value

For website operation, an accurate and unified date and time format has multiple values:

  • Improve user experience:The clear and understandable publication time makes it easy for readers to understand, enhancing the timeliness and readability of the content.
  • Optimize content management:Whether it is an article, product, or event, standardized date display helps users understand the lifecycle of the content and assist in decision-making.
  • Enhance brand professionalism:Details determine success or failure; a consistent date format reflects the meticulous and professional operation of the website.
  • Help SEO:Although it is not a direct SEO ranking factor, good user experience and content presentation help reduce the bounce rate and increase the duration of stay, indirectly enhancing the SEO effect.

ByarchiveListwithstampToDateThe perfect combination, Anqi CMS provides powerful tools for website operators, making timestamp formatting simple, flexible, and efficient, truly achieving the goal of serving technology for content and improving the overall operation efficiency and user satisfaction of the website.

Frequently Asked Questions (FAQ)

1. Ifitem.CreatedTimeEmpty or invalid timestamp,stampToDateHow will it be handled?Of Security CMSstampToDateThe tag design is relatively robust. If the input时间戳Parameter is empty(nil)or is not a valid 10-digit numeric timestamp, it will usually return an empty string, or return a default, non-error display result according to the internal implementation strategy to avoid page crash. In actual development, if you are worried about data irregularity, you can add it before the call{% if item.CreatedTime %}Such a judgment ensures that only valid timestamps are formatted.

2. BesidesstampToDateDoes AnQi CMS have other tags or filters for date formatting?The AnQi CMS template engine (similar to Django syntax) also provides some built-in filters, such asdateFilters. However, it should be noted that the documentation explicitly statesdateThe filter requires its input to be a Go languagetime.Timetype object, rather than the original timestamp. Therefore, if your data source is a timestamp (likeitem.CreatedTime)stampToDateIs a more direct and recommended solution. If your Go backend code has already converted the timestamp totime.Timean object and passed it to the frontend, thendatethe filter can also be used.

How to use different date formats on different pages while maintaining flexibility? stampToDateThe second parameter is a string, which means you can flexibly pass different format strings based on different page requirements. For example, on the article list page, it may only display"2006-01-02"(Year-Month-Date), and it can be displayed on the article detail page"2006年01月02日 15:04:05"(Precise to seconds). You can even store the format string in a variable to achieve more advanced dynamic formatting, thereby meeting the diverse needs of date and time display in different regions of the website.