Thymeleaf中使用三元表达式(a?b:c)根据日期选择调用片段的语法实现
实现Thymeleaf条件加载片段(三元表达式逻辑)
需求说明
当用户未选择任何日期时,加载dailyStatisticsFragmentsToday片段;当用户选择了完整的日期范围(起始和结束日期均已填写),加载dailyStatisticsFragmentsAll片段。
核心实现代码
直接在片段容器上使用Thymeleaf的三元表达式结合th:replace属性,即可实现动态切换:
<div id="fragments-container" th:replace="(${dataFormBean.selectSDate} == null || ${dataFormBean.selectEDate} == null) ? 'fragments/dailyStatisticsFragments :: dailyStatisticsFragmentsToday' : 'fragments/dailyStatisticsFragments :: dailyStatisticsFragmentsAll'"> </div>
逻辑说明
- 条件判断:检查表单绑定的
dataFormBean对象中,起始日期selectSDate或结束日期selectEDate是否为空值 - 三元分支:
- 满足条件(任一日期为空):加载今日统计片段
- 不满足条件(两个日期均已选择):加载全量统计片段
原表单代码
<form id="formBean" th:action="@{/dailyStatistics}" th:object="${dataFormBean}"> Select Range Date <button type="button" class="btn btn-primary btn-sm daterange" title="Date range"> <i class="far fa-calendar-alt"></i> </button> From: <input type="text" readonly="readonly" id="selectSdateInput" th:field="*{selectSDate}"> To: <input type="text" readonly="readonly" id="selectEdateInput" th:field="*{selectEDate}"> </form>
原片段代码参考
- 今日统计片段调用(默认):
<div id="fragments-container" th:replace="fragments/dailyStatisticsFragments :: dailyStatisticsFragmentsToday"></div>
- 全量统计片段调用(选日期后):
<div id="fragments-container" th:replace="fragments/dailyStatisticsFragments :: dailyStatisticsFragmentsAll"></div>
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

