如何在 Grails 中正确连接两个消息属性?

How to correctly concatenate two message properties in Grails?

同一消息 属性(编码为 HTML)在一个输入字段上正确呈现,同时它(也编码为 HTML)显示 HTML 标签另一个输入字段。这些发生在 GSP 视图中。

我想连接消息属性以避免违反 DRY 原则。

输入 1

<input type="text" class="freeform search-input" title="${g.message(code:"registration.classSearch.field.courseNumberLevels.placeholder.tooltip", encodeAs: "HTML")}">

输入 2 三元运算符的错误分支是我看到问题的地方。我没有删除三元以防万一它可能是问题的一部分。

<input title="${config.config.contains('keyword')? g.message(code:"registration.classSearch.field.keywordinputbox.placeholder.tooltip", encodeAs: "HTML"):g.message(code:"registration.classSearch.field.inputbox.placeholder.tooltip", encodeAs: "HTML") + "<br><br>" + g.message(code:"registration.classSearch.field.courseNumberLevels.placeholder.tooltip", encodeAs: "HTML")}">

从输入 2 中删除 encodeAs: "HTML" 会使其正确显示。

<input title="${config.config.contains('keyword')? g.message(code:"registration.classSearch.field.keywordinputbox.placeholder.tooltip", encodeAs: "HTML"):g.message(code:"registration.classSearch.field.inputbox.placeholder.tooltip", encodeAs: "HTML") + "<br><br>" + g.message(code:"registration.classSearch.field.courseNumberLevels.placeholder.tooltip")}"

删除两个 <br><br> 并没有达到预期的效果。将第一个 g.message 更改为纯文本消息 属性 也没有任何效果。

输入 1 的输出:

<input type="text" class="freeform search-input" title="<b>Undergraduate Level</b>:<br>0&amp;ndash;4999<br><br><b>Graduate Level</b>:</br>5000+">

输入 2 的输出 encodeAs:

<input title="These special characters are ignored: *^&amp;#39;!@$#&amp;amp;?[ ] ( ) |. The % is allowed.&amp;lt;b&amp;gt;Undergraduate Level&amp;lt;/b&amp;gt;:&amp;lt;br&amp;gt;0&amp;amp;ndash;4999&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&amp;lt;b&amp;gt;Graduate Level&amp;lt;/b&amp;gt;:&amp;lt;/br&amp;gt;5000+" type="text" class="freeform search-input">

没有encodeAs输入2的输出:

<input title="These special characters are ignored: *^&amp;#39;!@$#&amp;amp;?[ ] ( ) |. The % is allowed.<b>Undergraduate Level</b>:<br>0&amp;ndash;4999<br><br><b>Graduate Level</b>:</br>5000+" type="text" class="freeform search-input">

我希望它在有和没有串联的情况下表现相同,但事实并非如此。我们不应该以这种方式连接吗?

更新 这个 讨论了 HTML 编码以防止 XSS,这让我意识到 encodeAs 正在做它应该做的事情——将消息编码为 HTML。删除 encodeAs 允许 HTML 渲染而不是被编码为 HTML 实体。

但这仍然不能解释为什么输入 1 的 HTML 被渲染而输入 2 有 HTML 个实体。

连接两个消息属性

这个问题可以简化为 html 中的两个字符串的问题。

title = "${g.message(code:'1')}<br><br/>${g.message(code:'2')}"

所以如果不是单引号的话...请注意 Whosebug 甚至不会将您的输入 2 识别为 HTML...这是因为您在该行的最后。

这个 讨论了 HTML 编码以防止 XSS,这让我意识到 encodeAs 正在做它应该做的事情 - 将消息编码为 HTML。删除 encodeAs 允许 HTML 渲染而不是被编码为 HTML 实体。

因此,有两种可能的解决方法,因为我仍然不知道为什么 encodeAs 的行为似乎有所不同:

  1. 保留 message.properties 中的 HTML 并从 g.message 方法中删除 encodeAs: "HTML"
  2. 将原始消息分成多个部分并将 HTML 移动到 GSP