KnowSphere 主题开发快速上手

环境:Halo 2.26.0+,已安装并启用 KnowSphere。先在测试站验证免费文章、付费文章、会员、匿名与登录场景。

1. 检查插件与资源

插件通过主题 HeadProcessor 注入样式、脚本和 window.__KNOWSPHERE__。先在浏览器网络面板确认只加载一份资源。主题还应支持插件未安装的情况:

<th:block th:if="${pluginFinder.available('know-sphere') or pluginFinder.available('know-sphere-pro')}">
  <th:block th:with="ksInfo=${knowSphereFinder.getPluginInfo()}">
    <small th:text="${ksInfo.version}"></small>
  </th:block>
</th:block>

只有特殊页面未自动注入资源时才使用下例;不要与自动注入同时使用:

<th:block th:with="ksInfo=${knowSphereFinder.getPluginInfo()}">
  <link rel="stylesheet" th:href="${ksInfo.cssUrl}" />
  <script th:src="${ksInfo.jsUrl}" defer></script>
</th:block>

若目标运行环境不提供 pluginFinder,在主题设置中提供明确的插件集成开关,并在条件块内调用 Finder;不要先解析不存在的 Finder 再判断结果。

2. 保留正文处理链

文章页输出 Halo 提供的 post.content.content。KnowSphere 的服务端正文处理器负责试看、付费墙及解锁条件,不要在主题里读取原始快照绕过处理器:

<article>
  <h1 th:text="${post.spec.title}"></h1>
  <div class="post-content" th:utext="${post.content.content}"></div>
</article>

这里只允许输出 Halo 已处理的文章 HTML,不允许对访客输入使用 th:utext。付费墙可包含 ks-paywall 或 ks-countdown;不要在正文之外再输出完整文章。

3. 会员套餐与签到

<section th:with="plans=${knowSphereFinder.listMembershipPlans().collectList().block()}">
  <p th:if="${#lists.isEmpty(plans)}">暂无会员套餐</p>
  <article th:each="plan : ${plans}">
    <h2 th:text="${plan.title}"></h2>
    <p th:text="${plan.description}"></p>
    <span th:text="${plan.price}"></span><span>元</span>
  </article>
</section>
<ks-checkin-calendar title="每日签到"></ks-checkin-calendar>

MembershipPlanVo 使用 title,不是 displayName。购买应调用用户中心建单接口,由服务端定价;不要把页面显示金额当作付款依据。

4. 订单分页

<section th:with="result=${knowSphereFinder.listMyOrders(1, 10).block()}">
  <p th:if="${result == null or #lists.isEmpty(result.items)}">暂无订单,请先登录或创建订单。</p>
  <article th:if="${result != null}" th:each="order : ${result.items}">
    <span th:text="${order.orderNo}"></span>
    <span th:text="${order.productTitle}"></span>
  </article>
</section>

Finder 的“我的”接口由服务端确定身份,不接受主题传来的其他用户名。登录态、401/403 和空数据需要独立处理。

5. 下一步

阅读 完整集成指南、脚手架、Finder 合同 和 组件参考。发布前用未购买/已购买的不同账号交叉检查正文、订单、缓存及分享预览。