在网站运营中,文章详情页的用户评论功能是提升用户互动和网站活跃度的关键。安企CMS(AnQiCMS)提供了强大且灵活的评论管理能力,让您能够轻松地在文章详情页显示评论列表,并支持用户提交评论,甚至进一步增强评论功能。
1. 准备工作:理解评论机制与模板结构
在安企CMS中,每篇文章都可独立开启评论功能。当用户在文章详情页提交评论后,这些评论会关联到对应的文章。要实现评论的展示与提交,我们主要在文章详情页的模板(通常是 archive/detail.html 或自定义的文章详情模板)中进行操作。安企CMS采用GoLang模板引擎语法,与Django模板类似,通过特定的标签来调用数据和实现逻辑。
核心思想是:
- 显示评论列表:利用内置的评论列表标签
commentList,传入当前文章的ID来获取相关评论。 - 提交评论表单:创建一个HTML表单,将其提交到安企CMS提供的评论发布接口。
- 增强功能:根据需求,可集成验证码、评论点赞等。
2. 在文章详情页显示评论列表
要在文章详情页展示用户评论,您需要使用 commentList 标签。这个标签能够帮助您获取与当前文章关联的评论数据,并支持分页显示。
首先,请确保您的文章详情模板已经正确获取了当前文章的信息。在文章详情模板中,通常可以直接通过 archive.Id 来获取当前文章的ID。
接下来,在您希望显示评论列表的位置,插入以下代码:
{# 确保您已经获取了当前文章的ID,例如这里假设当前文章对象为 archive #}
<div class="comments-section">
<h3>用户评论 ({{ archive.CommentCount }}条)</h3>
{% commentList comments with archiveId=archive.Id type="page" limit="10" order="id desc" %}
{% for item in comments %}
<div class="comment-item">
<div class="comment-meta">
<span class="comment-author">
{% if item.Status != 1 %}
<!-- 如果评论处于审核中,可以显示不同的提示或用户名 -->
审核中用户: {{ item.UserName|truncatechars:6 }}
{% else %}
{{ item.UserName }}
{% endif %}
</span>
{% if item.Parent %}
<span class="reply-to">回复 {{ item.Parent.UserName }}</span>
{% endif %}
<span class="comment-time">{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}</span>
</div>
<div class="comment-content">
{% if item.Parent %}
<blockquote class="reply-quote">
{% if item.Parent.Status != 1 %}
该评论内容正在审核中...
{% else %}
{{ item.Parent.Content|truncatechars:100 }}
{% endif %}
</blockquote>
{% endif %}
{% if item.Status != 1 %}
<p>该评论内容正在审核中,请耐心等待。</p>
{% else %}
<p>{{ item.Content }}</p>
{% endif %}
</div>
<div class="comment-actions">
<a class="item vote-comment" data-id="{{ item.Id }}">
赞 (<span class="vote-count">{{ item.VoteCount }}</span>)
</a>
<a class="item reply-comment" data-id="{{ item.Id }}" data-user="{{ item.UserName }}">回复</a>
</div>
</div>
{% empty %}
<p class="no-comments">还没有评论,快来发表您的看法吧!</p>
{% endfor %}
{% endcommentList %}
{# 评论分页显示 #}
{% pagination pages with show="5" %}
<div class="comment-pagination">
{% if pages.PrevPage %}<a href="{{ pages.PrevPage.Link }}" class="prev-page">上一页</a>{% endif %}
{% for page_item in pages.Pages %}
<a href="{{ page_item.Link }}" class="page-number {% if page_item.IsCurrent %}current{% endif %}">{{ page_item.Name }}</a>
{% endfor %}
{% if pages.NextPage %}<a href="{{ pages.NextPage.Link }}" class="next-page">下一页</a>{% endif %}
</div>
{% endpagination %}
</div>
这段代码中:
archiveId=archive.Id:确保评论列表只显示当前文章的评论。type="page":开启分页功能,limit="10"则表示每页显示10条评论。order="id desc":按ID倒序排列,最新评论显示在最前面。item.Status != 1:评论状态判断,1表示审核通过。您可以在后台对评论进行管理和审核。item.Parent:用于处理评论回复,如果存在item.Parent,则表示这是一条对其他评论的回复。stampToDate:是安企CMS提供的格式化时间戳的标签。pagination标签则负责生成评论列表的分页链接。
3. 实现评论提交表单
用户提交评论需要一个表单,并将其数据发送到安企CMS的评论发布接口 /comment/publish。为了支持回复功能,表单中还需要一个可选的 parent_id 字段。
以下是一个基本的评论提交表单示例:
”`twig