-1

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.

Sarit Rotshild
  • 391
  • 3
  • 5
  • 21

1 Answers1

2

encodeAsHTML just escapes reserved HTML symbols (such as <) to an entity reference (&lt; 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>
Deigote
  • 1,721
  • 14
  • 15
  • @Deigot- how can I import to the tagLib this class. p.s I write in Grails . Should I write import java.net.URL? – Sarit Rotshild Sep 03 '15 at 12:31
  • @Deigot- I got an error -No signature of method: com.threebaysover.EventTagLib.isUrl() is applicable for argument types: (java.lang.String) values: [http://www.one.co.il/Article/15-16/1,1,3,0/256641.html?ref=hp] – Sarit Rotshild Sep 03 '15 at 12:58
  • There's a typo. `isUrl(text)` should be `isURL(text)`. I don't know where the EventTagLib.isUrl() is coming from since the example taglib is named ViewFormatterTagLib. So I'm assuming you named it something else. – Emmanuel Rosa Sep 03 '15 at 13:52