用胸腺渲染动态标签名称
有没有办法渲染模板中标签名称不变的标签?我想产生标题H1
,h2
,...或h6
,取决于页面模型的某些属性模板:
<h1 th:text="${model.title}" th:if="${model.level == 1}"></h1>
<h2 th:text="${model.title}" th:if="${model.level == 2}"></h2>
<h3 th:text="${model.title}" th:if="${model.level == 3}"></h3>
<h4 th:text="${model.title}" th:if="${model.level == 4}"></h4>
<h5 th:text="${model.title}" th:if="${model.level == 5}"></h5>
<h6 th:text="${model.title}" th:if="${model.level == 6}"></h6>
这可以以更聪明的方式完成吗?
Is there a way to render a tag with a tag name that is not constant in the template? I want to produce a heading tag h1
, h2
, ..., or h6
depending on some attribute of the page model like in the following template:
<h1 th:text="${model.title}" th:if="${model.level == 1}"></h1>
<h2 th:text="${model.title}" th:if="${model.level == 2}"></h2>
<h3 th:text="${model.title}" th:if="${model.level == 3}"></h3>
<h4 th:text="${model.title}" th:if="${model.level == 4}"></h4>
<h5 th:text="${model.title}" th:if="${model.level == 5}"></h5>
<h6 th:text="${model.title}" th:if="${model.level == 6}"></h6>
Can this be done in a more clever way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
th:utext
来输出UNESCAPED HTML。因此,类似这样的事情可以例如:但是,胸腺层不是为此用例设计的 - 将Unexaped HTML放入模板中是错误的,并且具有安全含义(尤其是如果您要使用用户输入),并且模板为现在很难阅读。
我建议将您的原始百里香叶放入片段中,然后使用它。
HTML:
片段:
You can use
th:utext
to output unescaped html. So something like this would work for example:However, Thymeleaf wasn't really designed for this use case -- putting unescaped HTML into your templates is error prone and has security connotations (especially if you are taking in user input) and the template is hard to read now.
I would recommend just putting your original Thymeleaf into a fragment and using that.
HTML:
Fragment:
这样的事情可能会起作用,但我怀疑它更可读性,因此我不建议这样做。由于对未来开发的调试可能比输入所有IF(或开关)更麻烦。
请记住,这只是模拟代码,它可能有一些错别字,但是这个想法应该正确
Something like this would probably work but i doubt it be more readable and as such i would not recommend doing so. As debugging for a future dev might be more trouble than typing out all the ifs (or a switch) is.
Do keep in mind that this is just mock code, it might have some typos but the idea should be correct