In website operation, user interaction is a key element in enhancing community activity.The comment like feature can not only encourage user participation, but also help website administrators identify popular comment content.For websites using AnQiCMS, to implement this feature and update the like count in real time, it can be done through the built-in template tags of the system and a bit of front-end JavaScript code.

Basic comment function: How to display the comment list

In the AnQi CMS, the core of the comment function lies incommentListTemplate tag.It allows you to flexibly display related comment content on the document detail page.Generally, we would place the comment list below the document content to guide users in participating in discussions.

Firstly, in your document detail template file (for examplearchive/detail.html), you need toarchive.IdGet the current article ID and then pass it as a parameter tocommentListA basic comment list display code might look like this:

<div class="comments-section">
    <h3>用户评论</h3>
    {% commentList comments with archiveId=archive.Id type="list" limit="10" %}
        {% for item in comments %}
            <div class="comment-item" id="comment-{{item.Id}}">
                <div class="comment-header">
                    <span class="username">{{item.UserName}}</span>
                    <span class="timestamp">{{stampToDate(item.CreatedTime, "2006-01-02 15:04")}}</span>
                </div>
                <div class="comment-content">
                    {% if item.Status != 1 %}
                        <p class="moderation-notice">该评论正在审核中...</p>
                    {% else %}
                        <p>{{item.Content}}</p>
                    {% endif %}
                </div>
                <div class="comment-actions">
                    <a href="javascript:;" class="like-button" data-comment-id="{{item.Id}}">
                        赞 (<span class="vote-count">{{item.VoteCount}}</span>)
                    </a>
                    {% if item.Parent %}
                        <div class="reply-to">回复 @{{item.Parent.UserName}}</div>
                    {% endif %}
                </div>
            </div>
        {% empty %}
            <p>目前还没有评论,快来发表你的看法吧!</p>
        {% endfor %}
    {% endcommentList %}
</div>

In this template code, we have set a unique ID for each comment item,id="comment-{{item.Id}}"and added a like button on it.data-comment-id="{{item.Id}}"The custom attribute, used to store the comment ID. In addition, we wrap the like count with a tag and assign<span>a tag and assignvote-countThe class name, convenient for subsequent updates of this value through JavaScript.{{item.VoteCount}}This is the number of likes that come with the comment list tag of the safe CMS.

To implement the comment like function

Security CMS provides a dedicated API interface for liking comments.When the user clicks the like button, we need to send a request to this interface from the front-end JavaScript to inform the system which comment has been liked.

The like API interface is:/comment/praiseIt receives a parameter through a POST request:idThis is the comment ID, which is returned by this interface. The data returned in JSON format includes the updated number of likes.

The following is a JavaScript code implemented using jQuery, which you can place in the template file.</body>Before the label, or in a separate JavaScript file:

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    // 监听所有具有 'like-button' 类名的元素的点击事件
    $('.like-button').on('click', function(e) {
        e.preventDefault(); // 阻止默认的链接跳转行为

        var $this = $(this); // 缓存当前点击的按钮
        var commentId = $this.data('comment-id'); // 获取评论ID

        if (!commentId) {
            console.error('评论ID未找到。');
            return;
        }

        // 发送AJAX POST请求到点赞接口
        $.ajax({
            url: '/comment/praise',
            method: 'POST',
            data: { id: commentId },
            dataType: 'json', // 预期服务器返回JSON数据
            success: function(response) {
                if (response.code === 0) { // 假设 code: 0 表示成功
                    // 更新点赞数
                    $this.find('.vote-count').text(response.data.vote_count);
                    alert(response.msg); // 提示用户点赞成功或取消成功
                } else {
                    alert(response.msg || '点赞操作失败,请重试。'); // 提示错误信息
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX请求失败:', textStatus, errorThrown);
                alert('网络错误或服务器异常,请稍后再试。');
            }
        });
    });
});
</script>

This JavaScript code will first execute after the page has loaded, for all elements with:like-buttonThe element binds the click event of the class name. When the user clicks these buttons, it retrieves the corresponding comment ID and sends a POST request to the interface via AJAX./comment/praiseThe interface sends a POST request.

Live update of like count

The key to live updating the number of likes lies in the successful AJAX requestsuccessCallback function. In the above JavaScript code, we have already included this part of the logic:

success: function(response) {
    if (response.code === 0) { // 假设 code: 0 表示成功
        // 更新点赞数
        $this.find('.vote-count').text(response.data.vote_count);
        alert(response.msg); // 提示用户点赞成功或取消成功
    } else {
        alert(response.msg || '点赞操作失败,请重试。'); // 提示错误信息
    }
}

When the Anqi CMS backend successfully processes the like request and returns data (response.code === 0),it will be)response.datainclude the latest)vote_count.$this.find('.vote-count').text(response.data.vote_count);The function of this line of code is:

  1. $this:refers to the current user's clicked like button(.like-button).
  2. .find('.vote-count'):search for the class named inside the current buttonvote-countThe element, which is used to display the number of likes<span>Label.
  3. .text(response.data.vote_count):“Set the<span>tag text content to the latest number of likes returned by the backend.

Thus, users can see the change in like counts immediately without refreshing the page, thereby obtaining a more fluid interactive experience.

Integrate it into your template.

To fully implement the comment liking function, you need:

  1. In the comment list template (such asarchive/detail.html)usingcommentListDisplay tags and add a like button to thedata-comment-idproperties andvote-countdisplay area.
  2. Introduce the jQuery library (if your website has not yet introduced it).
  3. Add the above JavaScript code to your template file, usually placed in</body>The tag should be closed before the DOM element is fully loaded.

By following these steps, you can add an interactive like feature to your CMS website's comment section.


Common Questions (FAQ)

1. Why doesn't the like count update in real time, or is there no reaction after clicking?

This is usually due to the incorrect execution of front-end JavaScript code or failed API requests.You can try to open the browser's developer tools (F12), switch to the "Console" (console) and "Network" (network) panels.

  • Console: Check for any JavaScript error messages.
  • NetworkAfter clicking the like button, observe whether there is a/comment/praiseInitiate a POST request and view the response status code (should be 200) and the returned data.If the request has not been sent, the status code is not 200, or the returned data format is incorrect, you need to check the JavaScript code or server configuration.Also, make sure you have correctly included the jQuery library.

2. How does AnQi CMS prevent users from maliciously liking or repeatedly liking?

Anqi CMS's/comment/praiseThe interface has built-in logic to prevent duplicate likes.In most cases, the system will judge based on the user's IP address and comment ID.If the same IP votes multiple times for the same comment within a short period of time, or votes again after having already voted, the system will recognize this and take appropriate action (such as blocking further votes and returning a prompt, or performing the unvote operation).The specific strategy is determined by the security CMS backend, and users do not need any additional processing on the frontend to obtain this security guarantee.

3. Can I customize the style and prompt information of the like button?

Of course, can. The style of the like button is completely determined by the front-end HTML structure and CSS style. You can modify.like-buttonand.vote-countEnglish CSS to beautify them. As for the hint information, in JavaScript'ssuccessanderror