我尝试使用encodeAsHTML(),如下所示:
<p class="common-textmb-30">${direction?.description?.encodeAsHTML()}</p>
其中“direction?.description”是用户在某些输入中输入的文本。
它没有检测到网址。
答案 0 :(得分:2)
encodeAsHTML
只是将保留的HTML符号(例如<
)转义为实体引用(前一个示例为<
),因此浏览器不会解释该文本,最初呈现的是。
您可以使用java类String
检测java.net.URL
是否有效:
boolean isURL(String someString) {
try {
new URL(someString)
} catch (MalformedURLException e) {
false
}
}
但不是你要放在视图中的东西。因此,您可以使用taglib:
class ViewFormatterTagLib {
static namespace = 'viewFormatter'
def renderAsLinkIfPossible = { attrs ->
String text = attrs.text
out << (
isURL(text) ? "<a href='${text}'>${text}</a>" : text
)
}
private boolean isURL(String someString) {
try {
new URL(someString)
} catch (MalformedURLException e) {
false
}
}
}
并在视图中执行:
<p class="common-textmb-30">
<viewFormatter:renderAsLinkIfPossible text="${direction?.description"/>
</p>