I tried encodeAsHTML() as the following:
<p class="common-textmb-30">${direction?.description?.encodeAsHTML()}</p>
where "direction?.description" is a text which the user enterd in some input.
It didn't detect the url.
I tried encodeAsHTML() as the following:
<p class="common-textmb-30">${direction?.description?.encodeAsHTML()}</p>
where "direction?.description" is a text which the user enterd in some input.
It didn't detect the url.
encodeAsHTML
just escapes reserved HTML symbols (such as <
) to an entity reference (<
for the previous example), so that the text is not interpreted by the browser, but presented as it originally was.
You can detect if an String
is a valid using the java class java.net.URL
:
boolean isURL(String someString) {
try {
new URL(someString)
} catch (MalformedURLException e) {
false
}
}
but is not something you would put in the view. You can therefore use a 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
}
}
}
and in the view just do:
<p class="common-textmb-30">
<viewFormatter:renderAsLinkIfPossible text="${direction?.description"/>
</p>