代碼以下前端
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; }
那麼我在前端循環獲取標籤名稱的代碼以下java
<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。
展現效果以下:
web
.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}
<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>
正確的展現效果以下:
數據庫