【问题标题】:Spring Boot Thymeleaf Model Attribute passing HTML tag to HTML PageSpring Boot Thymeleaf 模型属性将 HTML 标记传递到 HTML 页面
【发布时间】:2016-11-29 07:11:22
【问题描述】:

当我使用模型属性传递 HTML 标记时,它会错误传递而留下不需要的内容


@Controller
String rating = "<i class="fa fa-star" aria-hidden="true"></i><i class="fa fa-star" aria-hidden="true"></i><i class="fa fa-star-half-o" aria-hidden="true"></i><i class="fa fa-star-o" aria-hidden="true"></i><i class="fa fa-star-o" aria-hidden="true"></i>"

model.addAttribute("rating", rating);

HTML Page
<span th:text="${rating}"></span>

Result is 
"<i class="fa fa-star" aria-hidden="true"></i><i class="fa fa-star" aria-hidden="true"></i><i class="fa fa-star" aria-hidden="true"></i><i class="fa fa-star-o" aria-hidden="true"></i><i class="fa fa-star-o" aria-hidden="true"></i>"

正如我们所看到的,在我想要的字符串周围有引号,这些引号在传递时不会显示在其他字符串上,例如 header、text 或 int's。似乎只显示 HTML,当它的标签存在时

当我传入一个很棒的字体时,它会以应有的方式显示,直到您从检查元素中点击“编辑为 HTML”

<span>&lt;i class="fa fa-star" aria-hidden="true"&gt;&lt;/i&gt;</span>

感谢任何知道原因或解决方法的人

【问题讨论】:

标签: java spring-boot thymeleaf


【解决方案1】:

这是 th:text 属性的默认行为。如果你想让 Thymeleaf 尊重我们的 XHTML 标签而不是转义它们,你将不得不使用不同的属性:th:utext(用于“未转义的文本”);)

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
This will output our message just like we wanted it:
<p>Welcome to our <b>fantastic</b> grocery store!</p>

【讨论】:

  • 感谢您的回复。这就是解决方案。非常感谢您的帮助
猜你喜欢
  • 2021-09-16
  • 1970-01-01
  • 2017-06-21
  • 2017-10-01
  • 2016-07-12
  • 2019-02-10
  • 2017-10-14
  • 2018-12-16
  • 2019-12-07
相关资源
最近更新 更多