Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode an URL with Play 2

How can I encode an URL in a template with Play 2?

I search a helper like this:

<a href="@urlEncode(name)">urlEncode doesn't work now</a>

I have found a pull request, but this doesn't seem to work with the actual play 2.0.3 release.

like image 302
Sonson123 Avatar asked Sep 01 '12 09:09

Sonson123


People also ask

How do you encode a URL?

URL Encoding (Percent Encoding) URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.

What is %25 in a URL?

Reserved characters, such as the percent sign, are only valid to indicate special meaning, and they must be encoded when they are used without their special meaning. For example, to include a percent sign in a URL, you must encode it as “%25.”


2 Answers

As of 2.1 you can use @helper.urlEncode

<a href="@helper.urlEncode(foo)">my href is urlencoded</a>
like image 154
frostmatthew Avatar answered Sep 22 '22 10:09

frostmatthew


As I can see in linked ticked it will be resolved in Play 2.1

Quickest solution is placing ,method(s) for that in you controller (Application.java in this sample)

public static String EncodeURL(String url) throws java.io.UnsupportedEncodingException {
    url = java.net.URLEncoder.encode(url, "UTF-8");
    return url;
}

public static String EncodeURL(Call call) throws java.io.UnsupportedEncodingException {
    return EncodeURL(call.toString());
}

and then using it in the view as required at the moment:

<a href='@Application.EncodeURL(routes.Application.someAction())'>
    Encoded url form router</a>  <br/>

<a href='@Application.EncodeURL("/this/is/url/to/encode")'>
     Encoded url from string</a>  <br/>

<a href='@routes.Application.someAction()[email protected](routes.Application.someOtherAction())'>
     Url mixed normal+encoded</a>  <br/>
like image 43
biesior Avatar answered Sep 22 '22 10:09

biesior