thymeleaf中switch case多出一個空行


以下是thymeleaf3.0.5中文參考手冊.pdf》中的代碼,官方代碼沒有具體去查詢。

<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>

這樣最終生成代碼總會多出一個div。例如

<div>
<p>User is an administrator</p>
</div>

以下是筆者的代碼。

user實體綁定實體ApiUserDto相關字段如下

@Data
public class ApiUserDto extends ApiUser {
    private String certStatusLabel;
}

@Data
public class ApiUser{
       /***
     * 審核狀態 0 un certified //未認證(默認)
     *         1 unaudited  //待審核
     *         2 certified  //已認證
     */
    private Integer certStatus;
}

 

<div th:switch="${user.certStatus}">
    <div th:case="0" th:text="未認證" class="I124_name pageChange" data-page="/approve/index"></div>
    <div th:case="1" th:text="待審核" class="I124_name pageChange" data-th-data-page="${user.type=='personal'?'/approve/personal':'/approve/company'}"></div>
    <div th:case="2" th:text="已認證" class="I124_name pageChange" data-th-data-page="${user.type=='personal'?'/approve/personal':'/approve/company'}"></div>
</div>

生成效果

 

 

 顯然在以下情況下,那個class並沒有 最外層div,樣式效果有可能就有變化了。走樣?

解決方法1:

在sql語句層面額外生成一個屬性certStatusLabel綁定到ApiUserDto,其他屬性在頁面上使用SpringEL表達式判斷

select
            case cert_status WHEN 0 THEN '未認證' WHEN 1 THEN '待審核' WHEN 2 THEN '已認證' END certStatusLabel,
            count(n.id) notificationCount,
            count(u.id) appCount,
            IFNULL(u.avatar_url,'head_portrait2.png') avatar_url,
            u.*
        from api_user u left JOIN api_notification n
        on n.user_id = u.id
        LEFT JOIN api_app a on a.user_id = u.id
        where u.login_name = #{loginName} and u.`password` = #{encryptedPassword}

筆者前端代碼變成以下類似形式:

<div th:text="${user.certStatusLabel}" class="I124_name pageChange" data-th-data-page="${user.certStatus==0?'/approve/index':(user.certStatus==1)}"></div>

最終生成代碼:

 

弊端:此種情況維護的時候需要修改sql語句重啟web服務器 

完美解決方法:

使用th:block

<th:block th:switch="${user.certStatus}">
    <div th:case="0" th:text="未認證" class="I124_name pageChange" data-page="/approve/index"></div>
    <div th:case="1" th:text="待審核" class="I124_name pageChange" data-th-data-page="${user.type=='personal'?'/approve/personal':'/approve/company'}"></div>
    <div th:case="2" th:text="已認證" class="I124_name pageChange" data-th-data-page="${user.type=='personal'?'/approve/personal':'/approve/company'}"></div>
</th:block>

最終生成代碼:

 

 弊端:生成代碼上下文有空行,當然可以那幾個case放到同一樣,不過不方便維護,對於強迫症患者,來說比較致命。

 

如果你知道怎么把空行去除了,歡迎留言,筆者也是一個強迫症患者:)。

 

參考來源:

https://stackoverflow.com/questions/29657648/thymleaf-switch-statement-with-multiple-case

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM