Grails render() with a fragment parameter

坚强是说给别人听的谎言 提交于 2019-12-06 11:44:32

You cannot pass it to render(), because by the time you're actually invoking render(), the URL has already been determined and mapped to your action; all render is doing is controlling what gets written back to the response.

The fragment must already be in the URL before the rendering controller action gets called. Here's an example:

grails-app/controllers/MyController.groovy

class MyController {
    def foo = {
        render(view: 'foo')
    }

    def quux = {
        redirect(action: 'foo', fragment: 'baz')
    }
}

grails-app/views/my/foo.gsp

<html>
  <head>
    <title>Foo</title>
  </head>
  <body>
    <a id="bar">Bar</a>
    <g:each in="${0..100}"><br/></g:each>
    <a id="baz">Baz</a>
  </body>
</html>

With various URLs:

http://example.com/myapp/my/foo     - doesn't scroll to an anchor
http://example.com/myapp/my/foo#baz - scrolls to the 'baz' anchor
http://example.com/myapp/my/quux    - scrolls to the 'baz' anchor'

There is no way to specify a fragment directly with a grails render call, but in my code I'm using a work around that seems to provide most of the desired functionality with only a little extra complexity. The trick is to pass in the desired fragment reference as a part of the model, and then to act upon that reference in the GSP page. Thus, the render call in my controller looks like this:

def foo() {
    render(view : 'foo', model:[fragment:'myFragment'])
}

then, down in the GSP, I access the model with the following Javascript:

<g:javascript>
    if ("${fragment}") {
        window.location.href = "#${fragment}";
    }
</g:javascript>

The GSP will then tell your browser to jump forward to the desired anchor in the page (if any).

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