thymeleaf中switch case多出一个空行 解决方法1: 完美解决方法:

以下是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>

生成效果

thymeleaf中switch case多出一个空行
解决方法1:
完美解决方法:

 显然在以下情况下,那个class并没有 最外层div,样式效果有可能就有变化了。走样?

在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>

最终生成代码:

thymeleaf中switch case多出一个空行
解决方法1:
完美解决方法:

弊端:此种情况维护的时候需要修改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>

最终生成代码:

thymeleaf中switch case多出一个空行
解决方法1:
完美解决方法:

 弊端:生成代码上下文有空行,当然可以那几个case放到同一样,不过不方便维护,对于强迫症患者,来说比较致命。

如果你知道怎么把空行去除了,欢迎留言,笔者也是一个强迫症患者:)。

参考来源:

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