How to dynamically generate a custom field comment form with `guestbook` tag and adapt to different input types?

Calendar 👁️ 65

Managing website comments in AnQi CMS is a common requirement in daily operations, especially when we need to collect specific information. A flexible and customizable comment form is particularly important. AnQi CMS fully considers this need and provides powerfulguestbookTag, allowing us to easily dynamically generate a form with custom fields for comments, and adapt to various input types.

Comment form tag (guestbook) of power

The core lies inguestbookThe label allows us to dynamically obtain the comment form fields defined in the background. When used in the template{% guestbook fields %}...{% endguestbook %}then,fieldsThe variable will carry an array containing all custom message field definitions.This means we do not need to hard-code each form item, but instead, the system provides the structural information of these fields automatically based on the backend settings, which greatly improves the reusability and flexibility of templates.

The secret to dynamically generate form field secrets

fieldsEach element (usually nameditem) represents an independent message field, which contains the key information needed to generate a form item:

  • NameField display name, such as 'Your Name', 'Phone Number', etc.
  • FieldName: The unique identifier of the field, used to receive data from the backend when submitting a form. For example, if the backend defines a field named “Hobbies”, itsFieldNameIt could behobbies.
  • Type: This is the key to implementing different input types. Anqi CMS supports various field types, such astext(Single-line text),number(Number),textarea(Multi-line text),radio(Single selection),checkbox(Multiple choice) andselect(Dropdown select).
  • RequiredA boolean value indicating whether the field is required. On the front end, you can add HTML5 attributes or custom validation based on this property.requiredattributes or custom validation.
  • ContentThe default value of the field, usually used forplaceholderHint.
  • Items: When the field type isradio/checkboxorselectthen,ItemsIt will include an array listing all available options.

With this information, we can use it in the template.forLoop throughfieldsthe array and combineif/eliflogical judgmentitem.TypeThus, rendering the HTML form elements adapted for each field.

Here is a complete example code that demonstrates how to dynamically generate a form with different input types for comments:

<form method="post" action="/guestbook.html">
    {% guestbook fields %}
        {% for item in fields %}
        <div>
            <label>{{item.Name}}</label>
            <div>
                {% if item.Type == "text" or item.Type == "number" %}
                <input type="{{item.Type}}" name="{{item.FieldName}}" {% if item.Required %}required lay-verify="required"{% endif %} placeholder="{{item.Content}}" autocomplete="off">
                {% elif item.Type == "textarea" %}
                <textarea name="{{item.FieldName}}" {% if item.Required %}required lay-verify="required"{% endif %} placeholder="{{item.Content}}" rows="5"></textarea>
                {% elif item.Type == "radio" %}
                    {%- for val in item.Items %}
                    <input type="{{item.Type}}" name="{{item.FieldName}}" value="{{val}}" title="{{val}}"> {{val}}
                    {%- endfor %}
                {% elif item.Type == "checkbox" %}
                    {%- for val in item.Items %}
                    <input type="{{item.Type}}" name="{{item.FieldName}}[]" value="{{val}}" title="{{val}}"> {{val}}
                    {%- endfor %}
                {% elif item.Type == "select" %}
                <select name="{{item.FieldName}}">
                    {%- for val in item.Items %}
                    <option value="{{val}}">{{val}}</option>
                    {%- endfor %}
                </select>
                {% endif %}
            </div>
        </div>
        {% endfor %}

        {# 验证码字段,如果后台开启了验证码功能 #}
        <div style="display: flex; clear: both; margin-top: 15px;">
          <input type="hidden" name="captcha_id" id="captcha_id">
          <input type="text" name="captcha" required placeholder="请填写验证码" style="flex: 1; border: 1px solid #e6e6e6; padding: 0 10px; height: 38px; line-height: 38px; box-sizing: border-box;">
          <img src="" id="get-captcha" style="width: 120px;height: 38px;cursor: pointer; margin-left: 5px; border: 1px solid #e6e6e6;" />
          <script>
            document.addEventListener('DOMContentLoaded', function() {
              var captchaImg = document.getElementById('get-captcha');
              if (captchaImg) {
                captchaImg.addEventListener("click", function () {
                  fetch('/api/captcha')
                          .then(response => response.json())
                          .then(res => {
                            document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
                            captchaImg.setAttribute("src", res.data.captcha);
                          }).catch(err => console.error('获取验证码失败:', err));
                });
                // Initial load
                captchaImg.click();
              }
            });
          </script>
        </div>

        <div style="margin-top: 20px;">
            <button type="submit" style="padding: 10px 20px; background-color: #007bff; color: white; border: none; cursor: pointer;">提交留言</button>
            <button type="reset" style="padding: 10px 20px; background-color: #6c757d; color: white; border: none; cursor: pointer; margin-left: 10px;">重置</button>
        </div>
    {% endguestbook %}
</form>

In the code above, we render the corresponding HTML tags for each field type:

  • textandnumberType generation<input type="text">or<input type="number">.
  • textareaType generation<textarea>.
  • radio/checkboxandselectType will traverseitem.ItemsArray to generate individual options. It should be noted that,checkboxofnamethe attribute is usually appended at the end[]so that the backend can receive multiple selected values in an array format.
  • requiredThe addition of properties can take advantage of the built-in HTML5 form validation in the browser to enhance user experience.

Leave a message: backend interaction and captcha integration

The form submission address is fixed to/guestbook.htmlThe submission method isPOST. In addition to dynamically generated custom fields, Anqi CMS also requires some core fields such asuser_name(Name of the person leaving a message),contact(Contact information) andcontentThe message content must exist in the form and be submitted. These fields can be managed in the background message settings and can be set as required fields as needed.

To enhance security and prevent spam comments, Anqi CMS also supports integrated captcha.After the background comment captcha feature is turned on, we need to add the captcha input box and image display logic to the form.The code already includes the JS generation and display logic for the captcha, the user can refresh the captcha by clicking the image, and the input is submitted along with the form.

Summary

Of Security CMSguestbookThe label provides great convenience for customizing the website message form.By simply defining fields in the background, we can dynamically generate rich forms in the front-end template, to adapt to various information collection scenarios.This design not only improves development efficiency, but also brings more possibilities to website operations, allowing the website to interact more flexibly with users and collect the necessary data.


Related articles

How to determine if the current navigation item is the current page in the `navList` loop?

In website operation, a clear navigation structure is crucial for improving user experience.A good navigation not only helps visitors quickly find the information they need, but also guides users through visual cues (such as highlighting the current page) so that they always know where they are.In AnQi CMS, implementing this feature is quite intuitive and efficient, which is due to its powerful template tag system.

2025-11-08

How to use the `navList` tag to create a navigation bar with submenus in the Anqi CMS template?

In AnQi CMS template development, building a functional and user-friendly navigation bar is one of the core tasks of website frontend development.Especially when navigation needs to include multi-level sub-menus, the `navList` tag provided by Anqi CMS can help us efficiently meet this requirement.Understanding the core role of the `navList` tag The `navList` tag is a tool specifically used in the Anqi CMS template to retrieve website navigation data and display it on the page.

2025-11-08

How to display documents under the current category using the `categoryList` tag without including documents from subcategories?

When building a website with Anq CMS, we often encounter such a need: on a category page, we want to display only the documents that belong to the current category, and not mix in the document content of its subcategories.This is particularly important in scenarios where the content structure is clear and avoids redundancy.Today, let's discuss in detail how to accurately achieve this goal through the template tags of Anqi CMS. ### Understanding AnQiCMS Classification and Document Relationship AnQiCMS has always fully considered the flexibility of content hierarchy from the beginning of its design.A category can have subcategories

2025-11-08

How to build a multi-level category navigation in Anqi CMS template and judge whether each category has subcategories?

In today's increasingly rich website content, a clear and efficient navigation system is crucial for improving user experience and search engine optimization (SEO).Especially for websites with a large amount of content or multiple product categories, multi-level category navigation can help users quickly find the information they need while also showing the structural hierarchy of the website to search engines.Anqi CMS with its flexible and powerful template engine makes it simple and intuitive to build such a navigation.This article will deeply explore how to cleverly construct a multi-level classification navigation in Anqi CMS template, and intelligently judge whether each category contains subcategories

2025-11-08

How to display a document's comment list in Anqi CMS template, including reply and pagination features?

In Anqi CMS, add a comment list to the document content and enable it to have reply and pagination functions, which can greatly enhance the user interaction of the website.Users can express their opinions and discuss specific documents, which not only enriches the content ecosystem but also brings more vitality to the website. ### One: Displaying Comment Lists: The Foundation of Interaction To display comments on a document page, it mainly relies on the `commentList` tag built into Anqin CMS.This tag helps us easily get the comment data associated with the current document. First

2025-11-08

How to judge whether the comment is under review and display it conditionally using the `commentList` tag?

In website operation, comments are an important element in enhancing user interaction and community vitality.However, it is an indispensable link to review the comments submitted by users to ensure the health and quality of the website content.How can we flexibly display these comments in AnQi CMS, especially when they are still in the review stage, which has become a concern for many operators.It's good that AnQi CMS template tag system provides us with strong control, especially the `commentList` tag, which can help us easily implement conditional display of comments.

2025-11-08

How to create a customizable pagination component for the document list in Anqi CMS template?

It is crucial to display and manage document lists efficiently when building a content-rich website.Especially for sites with a large amount of content, a well-designed, feature-complete pagination component can not only greatly improve user experience but also optimize the website's SEO performance, helping search engines to better crawl and index content.AnQiCMS (AnQiCMS) with its flexible template engine and powerful tag features, allows us to easily create highly customizable pagination components for document lists.

2025-11-08

How to get the current page number, total number of pages, and home/last page links for the `pagination` tag?

AnQiCMS (AnQiCMS) is a powerful content management system that provides flexible and diverse ways to display content when building a website.Among them, the pagination function is crucial for list pages with a large amount of content, as it not only improves the user experience but also optimizes the website performance.Proficiently use the `pagination` tag, which can help us accurately control the display logic of pagination, thereby creating a more user-friendly and professional website.

2025-11-08