在游戏2中使用锚重定向

时间:2013-02-24 18:26:11

标签: java playframework-2.0

我正在寻找为控制器中返回的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使用addRef方法在游戏1中是可能的,但我在游戏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");
}

但它看起来很难看。

感谢您的帮助!祝你有个美好的一天!

2 个答案:

答案 0 :(得分:3)

在尝试回答这个问题之前。 我建议你改变你目前正在设置的任何行为。

因为,URL片段的目的只是客户端。这样的片段永远不会发送到服务器,所以反过来很麻烦。

然而,这是你可以遵循的(完全?)优雅解决方案的萌芽。

我要做的是让浏览器处理片段,以保持潜在的行为(f.i.转到ID甚至处理历史...)。

为此,您可以在implicit模板中添加main参数,该参数将定义网址应包含的片段:

@(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时),我们添加了一个脚本块,用于设置urlFragment中可用的哈希值。

这可能是一个开始,但是......想想整个场景的另一个解决方案。

答案 1 :(得分:3)

从Play 2.4开始,可以使用Call.withFragment()

routes.Application.index.withFragment("some-id").absoluteURL(request)

这是PR #4152添加的。