Is there a way to use render() with a fragment param so on page load it automatically scrolls to a specific part of the page? Similarly to how we can call
redirect(controller: "book", action: "show", fragment: "profile")
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).
来源:https://stackoverflow.com/questions/6861738/grails-render-with-a-fragment-parameter