- 用到的標簽有 th:each \ th:if \ key.current.key \ th:text
需求是展示文章的標簽名稱,blog 對象的標簽字段是tag(數據通常是java,xx,java-web等以逗號分割的),所以由后端傳到前端的數據是HashMap<String,List> ——(key是blog的id,List是分割后標簽名稱),
數據庫的數據格式如下
代碼如下
public ModelAndView index(ModelAndView mv){
mv.setViewName("index");
//最新博客
//最新文章 2條
List<Blog> blogs = blogService.getLatestBlog(3,"");
//熱門文章
mv.addObject("blogs",blogs);
HashMap<String,List<String>> mp = new HashMap<>();
for (Blog blog : blogs) {
mp.put(String.valueOf(blog.getId()), Arrays.asList(blog.getTags().split(",")));
}
mv.addObject("tags",mp);
return mv;
}
那么我在前端循環獲取標簽名稱的代碼如下
<div th:each="blogs:${blogs}">
<h2 class="indexBlogTitle" th:text="${blogs.title}">標題</h2>
<div class="items">
<!-- th:if 循環的時候判斷 文章id是否相同-->
<!-- tag.current.key 是取map的key-->
<!--tag.current.value 取blogid 對應標簽集合-->
<!--th:text 取標簽名稱-->
<a th:each="btag,tag:${tags}" th:if="${blogs.id} == ${tag.current.key}">
<span th:each="mytag:${tag.current.value}" th:text="${mytag}">
</span>
</a>
</div>
</div>
備注 Thymeleaf 取值key , value ;以及 循環中 th:if。
展示效果如下:

- 由於樣式如下,按照預期的結果 應該是每一個博客標簽的顏色是不同的,樣式代碼如下
.items a:nth-child(9n){background-color: #4A4A4A;}
.items a:nth-child(9n+1){background-color: #428BCA;}
.items a:nth-child(9n+2){background-color: #5CB85C;}
.items a:nth-child(9n+3){background-color: #D9534F;}
.items a:nth-child(9n+4){background-color: #567E95;}
.items a:nth-child(9n+5){background-color: #B433FF;}
.items a{opacity: 0.80;filter:alpha(opacity=80);color: #fff;background-color: #428BCA;display: inline-block;margin: 0 5px 5px 0;padding: 0 6px;line-height: 30px;
border-radius: 6px 6px 6px 6px;}
.items a:hover{opacity: 1;filter:alpha(opacity=100);}
.items h3{font-size: 18px;color: #666;border-bottom: 1px solid #eaeaea;background-color: #fbfbfb;margin: 0;padding: 11px 15px 10px;margin-bottom:15px}
- 將thymeleaf代碼進行修復,去掉了多余的span標簽,只保留 a 標簽
<div th:each="blogs:${blogs}">
<h2 class="indexBlogTitle" th:text="${blogs.title}">標題</h2>
<!-- 標簽優化后-->
<div class="items" th:each="btag,tag:${tags}" th:if="${blogs.id} == ${tag.current.key}">
<a th:each="mytag:${tag.current.value}" th:text="${mytag}"></a>
</div>
</div>
正確的展示效果如下:

