Ignore:
Timestamp:
Feb 8, 2011, 10:25:26 PM (14 years ago)
Author:
gav
Message:

New taglib, custom:easyUrl.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/features/taskProcedureRework/grails-app/taglib/CustomTagLib.groovy

    r672 r796  
     1//import org.apache.commons.validator.UrlValidator
     2import org.codehaus.groovy.grails.validation.routines.UrlValidator
     3import org.codehaus.groovy.grails.validation.routines.RegexValidator
    14
    25/**
     
    238241    } // jasperButtons
    239242
     243    /**
     244    * Easily create a link from a hopeful url string.
     245    * If the supplied url is not considered a valid url the string is simply displayed.
     246    *
     247    * Fields:
     248    *  url - String url to use.
     249    *  body - If no body is supplied in the GSP then url.encodeAsHTML() is displayed.
     250    *
     251    * Example:
     252    * <!--
     253    * <custom:easyUrl url="${docRef.location}" />
     254    * -->
     255    */
     256    def easyUrl = {attrs, body ->
     257
     258        def url = attrs.url
     259
     260        def html
     261
     262        body = body()
     263        if(!body)
     264            body = url.encodeAsHTML()
     265
     266        html = "${body}"
     267
     268        if(isURLValid(url)) {
     269            html = """
     270                        <a href="${url}">
     271                            ${html}
     272                        </a>
     273                        """
     274        }
     275
     276        out << html
     277    }
     278
     279    /**
     280    * Determine if a supplied string is considered a url or not.
     281    * The scheme/protocol can be adjusted, file:// has been excluded here.
     282    * A domainValidator regex is used to allow localhost domain.
     283    * A Grails branched version of commons.validator is used, this should
     284    * be compatible with the apache 1.4 version release.
     285    * See: http://jira.codehaus.org/browse/GRAILS-1692 for more on Grails url validation.
     286    */
     287    private Boolean isURLValid(url) {
     288
     289        def schemes = ["http","https", "ftp"] as String[]
     290        def domainValidator = new RegexValidator("localhost(:(\\d{1,5}))?")
     291        def validator = new UrlValidator(schemes, domainValidator, UrlValidator.ALLOW_2_SLASHES)
     292        return validator.isValid(url)
     293
     294    }
     295
    240296} // end class
Note: See TracChangeset for help on using the changeset viewer.