如何使用Play 2在模板中对URL进行编码?
我搜索一个这样的帮手:
<a href="@urlEncode(name)">urlEncode doesn't work now</a>
我找到了pull request,但这似乎不适用于实际播放的2.0.3版本。
答案 0 :(得分:24)
从2.1开始,您可以使用@helper.urlEncode
<a href="@helper.urlEncode(foo)">my href is urlencoded</a>
答案 1 :(得分:14)
正如我在linked ticked中看到的那样,它将在Play 2.1中得到解决
最快的解决方案是在您的控制器(此示例中为Application.java
)放置,方法
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());
}
然后根据需要在视图中使用它:
<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/>
答案 2 :(得分:1)
使用@ helper.urlEncode,如
@helper.urlEncode("http://www.giulio.ro/image/magictoolbox_cache/3bf842518f40ca6b8a10b619b8e02daf/6/2/621/thumb320x320/0804-427 - 255 lei.jpg")
返回
http%3A%2F%2Fwww.giulio.ro%2Fimage%2Fmagictoolbox_cache%2F3bf842518f40ca6b8a10b619b8e02daf%2F6%2F2%2F621%2Fthumb320x320%2F0804-427+-+255+lei.jpg
而我需要/预期的是
http://www.giulio.ro/image/magictoolbox_cache/3bf842518f40ca6b8a10b619b8e02daf/6/2/621/thumb320x320/0804-427%20-%20255%20lei.jpg
我用@ scott-izu这个解决方案 https://stackoverflow.com/a/9542781/99248