需求背景
最近在做的考试系统,进行到考试模块,该模块逻辑大致如下:从后台查询到各类型的题目数据,然后将数据放入前台模板中,生成一张试卷。前端使用的是HTML+ thymeleaf。在做这个功能时,遇到下列需求:
每一道题目的题干和选项,都有特定的id,这些id将会在提交答案和检测是否答题的功能中使用到。这就要保证每一个id都不同,因此,对于每一道题,我们都需要动态的拼接id,这样就可以保证每一道题的id都不同。而获取后台数据我才用的是thymeleaf循环遍历的 th:each
代码实现
这里放入试题的模板,可以看到,我通过==th:each=“single,singleStart: ${single}”==的语法拿到了后台保存的单选题List,并对它循环取值
在li标签中,我的id写法为:th:id="‘qu_0_’ + ${singleStart.index}",通过th语法,实现了对id属性的动态拼接,这样就保证了id不重复且和每道题有关联
<div class="test_content_nr" th:each="single,singleStart: ${single}">
<ul>
<li th:id="'qu_0_' + ${singleStart.index}">
<div class="test_content_nr_tt">
<i th:text="${singleStart.count}">1</i><font th:text="${single.quesTitle}">在生产管理信息系统中,下列操作步骤能正确将工单推进流程的是( )</font><b class="icon iconfont"></b>
</div>
<div class="test_content_nr_main">
<ul>
<li class="option">
<input type="radio" class="radioOrCheck" th:name="'answer' + ${singleStart.count}"
th:id="'0_answer_'+ ${singleStart.count} +'_option_1'" />
<label th:for="'0_answer_'+ ${singleStart.count} +'_option_1'">
A.
<p class="ue" style="display: inline;" th:text="${single.answerContent['A']}" >在失败页面重新发起</p>
</label>
</li>
<li class="option">
<input type="radio" class="radioOrCheck" th:name="'answer' + ${singleStart.count}"
th:id="'0_answer_'+ ${singleStart.count} +'_option_2'" />
<label th:for="'0_answer_'+ ${singleStart.count} +'_option_2'">
B.
<p class="ue" style="display: inline;"th:text="${single.answerContent['B']}">在缺陷单界面中点击“推进流程”按钮</p>
</label>
</li>
<li class="option">
<input type="radio" class="radioOrCheck" th:name="'answer' + ${singleStart.count}"
th:id="'0_answer_'+ ${singleStart.count} +'_option_3'" />
<label th:for="'0_answer_'+ ${singleStart.count} +'_option_3'">
C.
<p class="ue" style="display: inline;" th:text="${single.answerContent['C']}">在缺陷单界面中点击“提交”按钮</p>
</label>
</li>
<li class="option">
<input type="radio" class="radioOrCheck" th:name="'answer' + ${singleStart.count}"
th:id="'0_answer_'+ ${singleStart.count} +'_option_4'" />
<label th:for="'0_answer_'+ ${singleStart.count} +'_option_4'">
D.
<p class="ue" style="display: inline;" th:text="${single.answerContent['D']}">后台启动流程推进</p>
</label>
</li>
</ul>
</div>
</li>
</ul>
</div>
总结
th的语法功能十分强大,我也是才刚刚使用不久,还有更多强大的功能等我去探索,和大家一起学习