Thymeleaf 循環 List,Map複雜數據類型HashMap >----修復標籤樣式問題

  • 用到的標籤有 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;
    }

那麼我在前端循環獲取標籤名稱的代碼以下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}
  • 將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>

正確的展現效果以下:
數據庫

相關文章
相關標籤/搜索