GSP 页面中的三元运算符产生错误
Ternary Operator in GSP Page Produces Error
我目前正在升级到 Grails 4。GSP 页面无法识别三元运算符的使用。以下代码:
<td>${(user?.active) ? '<i class="icon icon-plus" style="color: green;"></i> <span style="color: green">Active</span>' : '<i class="icon-remove-circle" style="color: red;"></i> <span style="color: red">Inactive</span>'}</td>
打印字符串而不是显示 fontAwesome 图标。如果我删除 <i class = "icon... >
周围的单引号,则会产生以下错误。
unexpected token: ? @ line 190, column 275, it) { return (user?.active) ? <i class
^
这在以前的 Grails 版本中不是问题。除了将代码行转换为 if-else 语句之外,任何人都可以推荐一种解决方案吗?
这是显示内容的屏幕截图。
不是三元运算符未被识别,而是 HTML 显示为字符串而不是呈现的问题。这是因为 GSP 表达式(在 ${}
内)默认编码为 HTML。
要处理这种情况,请将您的表达式包装在 raw()
method:
<td>${raw(user?.active ? '<i class="icon icon-plus" style="color: green;"></i> <span style="color: green">Active</span>' : '<i class="icon-remove-circle" style="color: red;"></i> <span style="color: red">Inactive</span>')}</td>
如果您想为 entire page 更改此行为,您可以在 GSP 顶部添加:
<%@page expressionCodec="none" %>
如果你想改变这个default globally,你可以在application.yml
中设置:
grails:
views:
gsp:
codecs:
expression: none
我目前正在升级到 Grails 4。GSP 页面无法识别三元运算符的使用。以下代码:
<td>${(user?.active) ? '<i class="icon icon-plus" style="color: green;"></i> <span style="color: green">Active</span>' : '<i class="icon-remove-circle" style="color: red;"></i> <span style="color: red">Inactive</span>'}</td>
打印字符串而不是显示 fontAwesome 图标。如果我删除 <i class = "icon... >
周围的单引号,则会产生以下错误。
unexpected token: ? @ line 190, column 275, it) { return (user?.active) ? <i class
^
这在以前的 Grails 版本中不是问题。除了将代码行转换为 if-else 语句之外,任何人都可以推荐一种解决方案吗?
这是显示内容的屏幕截图。
不是三元运算符未被识别,而是 HTML 显示为字符串而不是呈现的问题。这是因为 GSP 表达式(在 ${}
内)默认编码为 HTML。
要处理这种情况,请将您的表达式包装在 raw()
method:
<td>${raw(user?.active ? '<i class="icon icon-plus" style="color: green;"></i> <span style="color: green">Active</span>' : '<i class="icon-remove-circle" style="color: red;"></i> <span style="color: red">Inactive</span>')}</td>
如果您想为 entire page 更改此行为,您可以在 GSP 顶部添加:
<%@page expressionCodec="none" %>
如果你想改变这个default globally,你可以在application.yml
中设置:
grails:
views:
gsp:
codecs:
expression: none