As an experienced CMS website operation personnel of an enterprise, I am very clear about the importance of high-quality content and smooth user experience in attracting and retaining users.The comment form is an important bridge for website interaction with users, and its correct rendering and processing in the template is directly related to whether users can conveniently and quickly contact us.Below, I will elaborate on how to render and process the comment form fields in the AnQiCMS template.
The location of the comment form template file
In AnQiCMS, the comment form usually has a dedicated template file to carry its content. According to the basic conventions of the system template creation, the template file of the comment page is usually located in the template directory.guestbook/index.htmlOr in the flattened modeguestbook.htmlUnderstanding this position is the first step in customization and development
UseguestbookLabel to get form fields
AnQiCMS provides a namedguestbookThe template tag is specifically used to retrieve the background configuration of the message form field.This tag allows us to dynamically render the corresponding form elements on the front end based on the flexible configuration of the backend.
The basic usage of tags is:{% guestbook fields %}...{% endguestbook %}.
Here,fieldsThis is the variable name defined for the array of form fields. This tag can accept an optional parametersiteIdUsed to call the specified site's comment form data in a multi-site environment, but usually not necessary for a single site.
fieldsA variable is an array object, which means we need to go throughforLoop through it to render each form field one by one.
Understand the structure of form fields deeply.
Inforthe loop,fieldseach element of the arrayitemIt represents a comment form field, it contains the following key properties, which guide us on how to correctly render the form:
Name: The display name of the form field, for example, "Your name", "Contact information", etc., which is the label text that users see on the page.FieldName: Form field variable name, which will be used as HTMLinput/textareaorselectelementnameAttribute value, used to submit data to the backend.Type: The type of form field, which determines which HTML form element we should render. AnQiCMS supports six types:text(Text type)number(Numeric type)textarea(Multiline text type)radio(Single selection type)checkbox(Multiple selection type)select(Dropdown selection type)
Required: A boolean value indicating whether this field is required. When its value istrueWhen, we should add to the HTML elementrequiredProperty.Content: The default value or placeholder text for form fields, for text input boxes or multi-line text boxes, this is usually asplaceholderthe value of the attribute.Items: Only when the form type isradio/checkboxorselectdoes this array exist. It contains all the available option values, and we need to traverse this array again to render these options.
Render the comment form dynamically
Combining the structure of the above fields, we can write general code in the template to dynamically generate forms. The core idea is to useforLoop throughfieldsThen, based onitem.TypeThe value is used to make conditional judgments, rendering different HTML form elements.
The following is a detailed code snippet that shows how to dynamically render forms based on field types.
<form method="post" action="/guestbook.html">
{% guestbook fields %}
{% for item in fields %}
<div class="form-group">
<label for="{{ item.FieldName }}">{{ item.Name }}{% if item.Required %}<span class="text-danger">*</span>{% endif %}</label>
<div>
{% if item.Type == "text" or item.Type == "number" %}
<input type="{{ item.Type }}" name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %}
placeholder="{{ item.Content }}" autocomplete="off" class="form-control">
{% elif item.Type == "textarea" %}
<textarea name="{{ item.FieldName }}" id="{{ item.FieldName }}"
{% if item.Required %}required{% endif %}
placeholder="{{ item.Content }}" rows="5" class="form-control"></textarea>
{% elif item.Type == "radio" %}
{% for val in item.Items %}
<label class="radio-inline">
<input type="radio" name="{{ item.FieldName }}" value="{{ val }}" {% if item.Required and loop.first %}required{% endif %}> {{ val }}
</label>
{% endfor %}
{% elif item.Type == "checkbox" %}
{% for val in item.Items %}
<label class="checkbox-inline">
<input type="checkbox" name="{{ item.FieldName }}[]" value="{{ val }}" {% if item.Required and loop.first %}required{% endif %}> {{ val }}
</label>
{% endfor %}
{% elif item.Type == "select" %}
<select name="{{ item.FieldName }}" id="{{ item.FieldName }}" class="form-control" {% if item.Required %}required{% endif %}>
{% for val in item.Items %}
<option value="{{ val }}">{{ val }}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
{% endfor %}
<div class="form-group">
<div>
<button type="submit" class="btn btn-primary">提交留言</button>
<button type="reset" class="btn btn-secondary">重置</button>
</div>
</div>
</form>
This code is first wrapped in a<form>Its label,actionproperty points to/guestbook.htmlThis is the default message submission interface for AnQiCMS. Inside the loop, we render the corresponding HTML form elements for differentitem.TypeRendering the corresponding HTML form element. For example,textandnumberType, rendering<input>Label; fortextarea, rendering<textarea>; for selecting type (radio/checkbox/select), will further loopitem.ItemsGenerate options.item.RequiredThe attribute is used to dynamically add HTML.requiredAttribute to implement client-side required validation.
Submission and data processing of the message form.
When the user fills in and submits the form, the data will be sent to/guestbook.html. In addition to the above dynamically generated custom fields, AnQiCMS also requires submission of several fixed core fields:
user_name: The name of the user who leaves a message, this field is required.contact: The contact information of the user, such as phone number, landline, WeChat ID, QQ number, etc., this field is also required.content: The specific content of the message, this field is also required.- Other custom field: According to the backend configuration, these fields may be required or optional.
return(Optional): Used to specify the format of the backend returned data. If the value ishtml(Default), the backend may return an HTML page; if the value isjson, the backend will return data in JSON format, which is very useful when performing AJAX submissions.
To better control the form structure, you can also not rely on it completelyguestbookLabel the loop output, rather than manually constructing a form, only dynamically rendering for the extra fields customized by the backend. For example, you can hard codeuser_name/contactandcontentfields, then only loop renderguestbookFields provided by the label.
Enhance security by combining captcha.
To prevent malicious submissions and spam, the comment form usually needs to integrate captcha functionality. AnQiCMS throughtag-/anqiapi-other/167.htmlThe document provides a method to enable captcha in comments or replies.
First, make sure in the AnQiCMS background.Global settings -> Content settingsMarkdown editor is enabled (although the document describes the Markdown editor, the captcha feature is mentioned here, which may be a cross-reference in document writing, usually the captcha settings will be in a separate "captcha settings" or "security settings").
Then, in your comment form, you need to add two hidden fields and one for displaying the captcha image.<img>Label, and cooperate with JavaScript to dynamically obtain and refresh the captcha:
<div class="form-group captcha-group">
<label for="captcha">验证码{% if item.Required %}<span class="text-danger">*</span>{% endif %}</label>
<div style="display: flex; align-items: center;">
<input type="hidden" name="captcha_id" id="captcha_id">
<input type="text" name="captcha" required placeholder="请填写验证码" class="form-control" style="flex: 1; margin-right: 10px;">
<img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #ccc;" alt="验证码" />
</div>
</div>
<script>
// 使用原生JS获取和刷新验证码
document.getElementById('get-captcha').addEventListener("click", function (e) {
fetch('/api/captcha')
.then(response => {
if (!response.ok) {
throw new Error('网络请求失败');
}
return response.json();
})
.then(res => {
if (res.code === 0) {
document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
} else {
console.error('获取验证码失败:', res.msg);
alert('获取验证码失败,请重试!');
}
})
.catch(err => {
console.error('获取验证码异常:', err);
alert('获取验证码时发生错误,请检查网络或稍后再试。');
});
});
// 页面加载后自动点击一次,获取初始验证码
document.getElementById('get-captcha').click();
</script>
This code sends a request to the interface using JavaScript to/api/captchaobtain the captcha.captcha_idand imagesrcand fill it into the form and image elements. When the user clicks the captcha image, it triggers a refresh operation.
Summary
The process of rendering and handling the message form fields in AnQiCMS templates is a combination of backend configuration and frontend template dynamic rendering. ThroughguestbookLabel, we can flexibly obtain the form structure defined by the background;By means of conditional judgment and loops, we can transform these structures into fully functional HTML forms;And integrating the captcha mechanism further enhances the security of the form.Mastering these methods will help you provide users with an efficient, secure, and user-friendly comment interaction interface.
Frequently Asked Questions (FAQ)
Why did I render the comment form according to the document, but it did not succeed after submission?
Firstly, please check your formactionIs the property correctly pointed to/guestbook.html. Secondly, confirm whether you have included all required fields:user_name/contact/contentand all other fields marked as 'required' by the backend. If captcha is integrated, make surecaptcha_idandcaptchathe field is also submitted correctly andcaptcha_idthe value is from/api/captchaThe interface retrieves. Check the browser console network requests, view the submitted response information, usually you can find the specific error cause.
Can I submit the message form via AJAX instead of page redirection?
Yes, AnQiCMS supports AJAX submission. You need to add a hidden field in the form<input type="hidden" name="return" value="json">. When this field exists, the backend will return JSON formatted data (usually containingcodeandmsg). Front-end JavaScript can accessfetchorjQuery.ajaxSubmit form data in this way and process the returned JSON data accordingly, for example, display success or failure messages without page jumping.
How to customize the style of the comment form?
The style of the comment form is completely controlled by your frontend CSS.After rendering the HTML form elements in the template, you can apply custom styles to them like any other HTML element, using CSS selectors (such as class names, IDs, or element types).It is recommended to add a specific element outside the form elementdivorformLabel, and specify a unique class name or ID for it to control its style more accurately, to avoid style conflicts with other parts of the website.