




























这篇文章 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>
插入以下代码到页面中,之后调用 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>
欢迎留言支持/交流
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。