我正在寻找将 anchor 添加到 Controller 中返回的 url 的可能性:
public static Result open(String id) {
// here I want to add acnhor like #foo to the produced url
return redirect(routes.MyPage.show(id));
}
我found在 play 1 中使用 addRef
方法是可能的,但我在 play 2 中找不到该方法的任何替代方法。
当然我可以像这样使用连接:
public static Result open(String id) {
// here I want to add acnhor like #foo to the produced url
return redirect(routes.MyPage.show(id).url + "#foo");
}
但是看起来很丑。
感谢您的帮助!祝你有美好的一天!
最佳答案
在尝试回答该问题之前。 我应该建议您更改当前设置的任何行为。
因为,URL 片段的目的只是客户端。这样的片段永远不会发送到服务器,因此做相反的事情很麻烦。
但是,这是您可以遵循的(相当?)优雅解决方案的雏形。
我将尝试做的是让浏览器处理片段,以保留潜在的行为(例如转到 ID 甚至处理历史...)。
为此,您可以在 main
模板中添加一个 implicit
参数,它将定义 URL 应具有的片段:
@(title: String)(content: Html)(urlFragment:Option[UrlFragment] = None)
如您所见,我将参数包装在 Option
中并将其默认设置为 None
(以避免 AMAP 污染)。
此外,它只是包装了一个 String
,但您可以单独使用 String
—— 使用专用类型将强制执行语义。这是定义:
case class UrlFragment(hash:String)
非常简单。
现在这里是如何告诉浏览器去处理它。在 head
元素末尾和 body
开始之前,只需添加以下内容:
@urlFragment.map { f =>
<script>
$(function() {
//after everything is ready, so that other mechanism will be able to use the change hash event...
document.location.hash = "@Html(@f.hash)";
});
</script>
}
如您所见,使用 map
(即当 urlFragment
不是 None
时)我们添加一个脚本 block 来设置散列在 urlFragment
中可用。
这可能是一个开始,但是......为整个场景考虑另一种解决方案。
关于java - 在 Play 2 中使用 anchor 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055010/