本站在允许 JavaScript 运行的环境下浏览效果更佳

在 Halo CMS 中通过模板实现随机文章跳转功能

这篇文章 Thymeleaf 随机数生成与格式化详解(整数/小数/浮点数) 的一个应用示例。

纯 Thymeleaf 模板实现

<a
  th:with="allPostList=${postFinder.listAll()},
    randomIndex=${T(java.lang.Math).floor(T(java.lang.Math).random()*#lists.size(allPostList))},
    postPermalink=${allPostList[randomIndex].status.permalink}"
  th:href="${postPermalink}"
>随机文章</a>

结合 Javascript 使用

插入以下代码到页面中,之后调用 toRandomPost() 即可跳转到随机博文。

<script
  th:inline="javascript"
  th:with="allPostList=${postFinder.listAll()},
    randomIndex=${T(java.lang.Math).floor(T(java.lang.Math).random()*#lists.size(allPostList))},
    postPermalink=${allPostList[randomIndex].status.permalink}"
>
    function toRandomPost() {
        let permalink = /*[[${postPermalink}]]*/ "/";
        
        // 选择任意方法跳转
        // window.open(permalink);
        // pjax.loadUrl(permalink);
        window.location.href = permalink;
    }
</script>

省略中间变量也是可以的

<script
  th:inline="javascript"
  th:with="allPostList=${postFinder.listAll()},
    randomIndex=${T(java.lang.Math).floor(T(java.lang.Math).random()*#lists.size(allPostList))},
    postPermalink=${allPostList[randomIndex].status.permalink}"
>
    function toRandomPost() {
        // 选择任意方法跳转
        // window.location.href = /*[[${postPermalink}]]*/ "/";
        // pjax.loadUrl(/*[[${postPermalink}]]*/ "/");
        window.open(/*[[${postPermalink}]]*/ "/");
    }
</script>

拓展

在上面代码中 allPostList[randomIndex] 返回的是 ListedPostVo 类型的变量。
借此你可以拿到文章更多相关信息,如:标题,创建时间,发布时间,是否置顶,摘要内容等。
以下的两个示例添加了获取文章标题的部分。

<a
  th:with="allPostList=${postFinder.listAll()},
    randomIndex=${T(java.lang.Math).floor(T(java.lang.Math).random()*#lists.size(allPostList))},
    postPermalink=${allPostList[randomIndex].status.permalink},
    postTitle=${allPostList[randomIndex].spec.title}"
  th:href="${postPermalink}"
  th:text="${postTitle}"
></a>
<script
  th:inline="javascript"
  th:with="allPostList=${postFinder.listAll()},
    randomIndex=${T(java.lang.Math).floor(T(java.lang.Math).random()*#lists.size(allPostList))},
    postPermalink=${allPostList[randomIndex].status.permalink},
    postTitle=${allPostList[randomIndex].spec.title}"
>
    <!--/* 小技巧:写在此处的注释在模板渲染后会去掉,可减小页面体积 */-->
    function toRandomPost() {
        // <!--/* 弹出提示框 显示文章标题 */-->
        alert(/*[[${postTitle}]]*/ "");
        
        // <!--/* 选择任意方法打开链接 */-->
        // window.open(/*[[${postPermalink}]]*/ "/");
        // pjax.loadUrl(/*[[${postPermalink}]]*/ "/");
        window.location.href = /*[[${postPermalink}]]*/ "/";
    }
</script>

实现示例

结语

欢迎留言支持/交流


1
上一篇 Folo 认证功能反成漏洞?警惕 RSS 订阅源所有权被恶意盗取风险
下一篇 从沉默展柜到时代回响:731部队罪证陈列馆参访手记