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.
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.
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.”
As of 2.1 you can use @helper.urlEncode
<a href="@helper.urlEncode(foo)">my href is urlencoded</a>
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/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With