Groovy-如何识别文本中的URL并将其显示为超链接

时间:2015-09-03 10:58:50

标签: grails groovy hyperlink gsp

我尝试使用encodeAsHTML(),如下所示:

<p class="common-textmb-30">${direction?.description?.encodeAsHTML()}</p>

其中“direction?.description”是用户在某些输入中输入的文本。

它没有检测到网址。

1 个答案:

答案 0 :(得分:2)

encodeAsHTML只是将保留的HTML符号(例如<)转义为实体引用(前一个示例为&lt;),因此浏览器不会解释该文本,最初呈现的是。

您可以使用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>