As an experienced security CMS website operations person, I am very clear about the importance of high-quality content and smooth user experience in attracting and retaining users.The comment form acts as an important bridge for interaction between the website and users. Its correct rendering and processing in the template is directly related to whether users can conveniently and quickly get in touch with us.Below, I will elaborate on how to render and process 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 system templates, the template file for the comment page is usually located in the template directory.guestbook/index.htmlor the flattened modeguestbook.html. Understanding this position is the first step for customization and development.
UseguestbookLabel to get form field
AnQiCMS provides a namedguestbookThe template tag, specifically used to retrieve the backend configuration of the comment form fields.This tag allows us to dynamically render the corresponding form elements on the front end based on the flexible configuration on the back end.
The basic usage of the tag is:{% guestbook fields %}...{% endguestbook %}Here,.fieldsThis is the variable name defined for the array of form fields we have received. This label can accept an optional parametersiteIdUsed to call the specified site's comment form data in a multi-site environment, but usually no need to fill in for a single site.
fieldsA variable is an array object, which means we need to go throughforIterate over it to render each form field one by one.
Understand the structure of form fields deeply.
Inforin the loop,fieldsevery element of the arrayitemRepresent a form field for a comment, it includes the following key properties, which will guide us on how to correctly render the form:
NameThe display name of form fields, such as "Your NameFieldName: Form field variable name, which will be used as HTMLinput/textareaorselect元素的nameAttribute value, used to submit data to the backend.Type: 表单字段的类型,它决定了我们应该渲染哪种HTML表单元素。AnQiCMS支持六种类型:text(文本类型)number(数字类型)textarea(Multi-line text type)radio(Single selection type)checkbox(Multiple selection type)select(Drop-down selection type)
Required: A boolean value indicating whether this field is required. When its value istrueWhen, we should add to the HTML elementrequiredproperties.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 exists when the form type isradio/checkboxorselect. It contains all the available option values, and we need to traverse this array again to render these options.
Dynamic rendering of the message form
Combine the above field structure, we can write general code in the template to dynamically generate forms. The core idea is to useforto iteratefields, then according toitem.TypeThe value is used to make conditional judgments and render 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>tag, itsactionthe attribute points to/guestbook.html, which is the default comment submission interface of AnQiCMS. Inside the loop, we handle differentitem.TypeRender the corresponding HTML form element. For example,textandnumbertype, render<input>tag; fortextarea, render<textarea>; for selection type,radio/checkbox/select),则会进一步循环item.Items来生成选项。item.Required属性被用来动态添加HTML的required属性,以实现客户端的必填验证。
留言表单的提交与数据处理
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 the submission of several fixed core fields:
user_name: Leave a message, the name of the user is required for this field.contact: Contact information of the user, such as phone number, landline, WeChat ID, QQ number, etc., this field is also required.content: Leave a specific message. This field is also required.- other custom fields: These fields may be required or optional depending on the backend configuration.
return(Optional): Used to specify the format of the data returned by the backend. If the value ishtml(default), the backend may return an HTML page; if the value isjsonThe backend will return data in JSON format, which is very useful when submitting AJAX requests.
You can also not rely entirely on the form structure for better control.guestbookThe loop output of labels is not manual form construction, but only dynamic rendering for additional fields customized by the backend. For example, you can hard codeuser_name/contactandcontentfields, and then only render in a loopguestbookLabel provided custom field.
Combine captcha to enhance security.
To prevent malicious submissions and spam, comment forms usually need to integrate captcha functionality. AnQiCMS throughtag-/anqiapi-other/167.htmlThe document provides the method to enable captcha in comments or replies.
Firstly, make sure that in the AnQiCMS background,Global Settings -> Content Settings中文启用了Markdown编辑器(尽管文档描述的是Markdown编辑器,但验证码功能在此处被提及,可能是一个文档编写上的交叉引用,通常验证码设置会在单独的“验证码设置”或“安全设置”中)。
Then, in your comment form, you need to add two crucial hidden fields and one for displaying the verification code image<img>Label, and use JavaScript to dynamically fetch 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/api/captchainterface to get the captcha'scaptcha_idwith imagesrc, and fill it into the form and image elements. When the user clicks the captcha image, a refresh operation will be triggered.
Summary
In AnQiCMS template, rendering and processing the留言表单 fields is a process that combines backend configuration with frontend template dynamic rendering. Throughguestbook标签,我们可以灵活地获取后台定义的表单结构;通过条件判断和循环,我们可以将这些结构转化为功能完备的HTML表单;而集成验证码机制则进一步提升了表单的安全性。Mastery of these methods will help you provide users with an efficient, secure, and user-friendly comment interaction interface.
Common Questions and Answers (FAQ)
Why did the form submission not succeed after rendering it according to the document?
Firstly, please check your formactionIs the attribute correctly pointing?/guestbook.html. Secondly, confirm that you have included all required fields:user_name/contact/content, as well as all other fields marked as 'required' by the backend. If captcha integration is enabled, please make surecaptcha_idandcaptchathe field is also submitted correctly, andcaptcha_idthe value is from/api/captchaInterface obtained. Check the browser console's network requests to view the submitted response information, and you can usually find the specific error cause.
Can I submit the message form using AJAX instead of page jump?
Yes, AnQiCMS supports AJAX submission. You need to add a hidden field to the form<input type="hidden" name="return" value="json">。When this field exists, the backend will return data in JSON format (usually containingcodeandmsg)。Front-end JavaScript can accessfetchorjQuery.ajaxSubmit form data in various ways and process the returned JSON data accordingly, such as displaying success or failure messages without page redirection.
How to customize the style of the comment form?
The style of the comment form is completely controlled by your frontend CSS.After rendering HTML form elements in the template, you can apply custom styles to them as you would with any other HTML elements, using CSS selectors (such as class names, IDs, or element types).divorformTags, and specify unique class names or IDs for them, so that you can control their styles more accurately and avoid style conflicts with other parts of the website.