Encode an URL with Play 2

为君一笑 提交于 2019-12-04 10:32:03

问题


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.


回答1:


As of 2.1 you can use @helper.urlEncode

<a href="@helper.urlEncode(foo)">my href is urlencoded</a>



回答2:


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()?encoded=@Application.EncodeURL(routes.Application.someOtherAction())'>
     Url mixed normal+encoded</a>  <br/>



回答3:


Using @helper.urlEncode as in

@helper.urlEncode("http://www.giulio.ro/image/magictoolbox_cache/3bf842518f40ca6b8a10b619b8e02daf/6/2/621/thumb320x320/0804-427 - 255 lei.jpg")

returned

http%3A%2F%2Fwww.giulio.ro%2Fimage%2Fmagictoolbox_cache%2F3bf842518f40ca6b8a10b619b8e02daf%2F6%2F2%2F621%2Fthumb320x320%2F0804-427+-+255+lei.jpg

while what I needed/expected was

http://www.giulio.ro/image/magictoolbox_cache/3bf842518f40ca6b8a10b619b8e02daf/6/2/621/thumb320x320/0804-427%20-%20255%20lei.jpg

I used @scott-izu this solution https://stackoverflow.com/a/9542781/99248



来源:https://stackoverflow.com/questions/12226508/encode-an-url-with-play-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!