【问题标题】:Grails render() with a fragment parameter带有片段参数的 Grails render()
【发布时间】:2011-10-15 06:14:32
【问题描述】:

有没有办法将 render() 与片段参数一起使用,以便在页面加载时自动滚动到页面的特定部分?类似于我们如何调用

redirect(controller: "book", action: "show", fragment: "profile")

【问题讨论】:

    标签: grails grails-controller


    【解决方案1】:

    您不能将其传递给render(),因为当您实际调用render() 时,URL 已经已经确定并映射到您的操作;渲染所做的只是控制写回响应的内容。

    在调用渲染控制器操作之前,片段必须已经在 URL 中。这是一个例子:

    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>
    

    各种网址:

    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'
    

    【讨论】:

    • 我现在不使用redirect() 的原因是我需要保留模型。有没有常见的解决方法?首先想到的是这样的:code class MyController { def model = [:] def foo = { render(view: 'foo', model: model) } def quux = { model.message = '嘿你'重定向(动作:'foo',片段:'baz')}}code
    • @Slavko - 我想我明白你在做什么;我得考虑一会儿。一种选择是使用会话来保留模型,但这不是很优雅。
    • 为什么第三个例子滚动到baz锚点?
    • @spartacus - 因为控制器中的 quux 操作重定向到 /foo#baz
    【解决方案2】:

    无法使用 grails 渲染调用直接指定片段,但在我的代码中,我使用了一种变通方法,它似乎提供了大部分所需的功能,但只增加了一点点额外的复杂性。诀窍是将所需的片段引用作为模型的一部分传入,然后在 GSP 页面中对该引用进行操作。因此,我的控制器中的渲染调用如下所示:

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

    然后,在 GSP 中,我使用以下 Javascript 访问模型:

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

    然后,GSP 将告诉您的浏览器向前跳转到页面中所需的锚点(如果有)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 2021-12-08
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多