代码之家  ›  专栏  ›  技术社区  ›  Constantin

Grails索引页的最佳实践

  •  27
  • Constantin  · 技术社区  · 16 年前

    在Grails应用程序中填充索引页模型的正确方法是什么?默认情况下没有indexcontroller,是否有其他机制可以将这个和那个列表获取到模型中?

    4 回复  |  直到 14 年前
        1
  •  36
  •   Ed.T    16 年前

    我不会说这是正确的方法,但这是一种开始的方法。用一个控制器作为默认值并不需要太多。添加到urlmappings.groovy的映射:

    class UrlMappings {
        static mappings = {
          "/$controller/$action?/$id?"{
                constraints {
                    // apply constraints here
                }
            }
          "500"(view:'/error')
         "/"
            {
                controller = "quote"
            }
        }
    }
    

    然后向现在的默认控制器添加索引操作:

    class QuoteController {
    
        def index = {
            ...
        }
    }
    

    如果要加载的内容已经是另一个操作的一部分,只需重定向:

    def index = {
        redirect(action: random)
    }
    

    或者为了真正实现重用,将逻辑放入服务中:

    class QuoteController {
    
        def quoteService
    
        def index = {
            redirect(action: random)
        }
    
        def random = {
            def randomQuote = quoteService.getRandomQuote()
            [ quote : randomQuote ]
        }
    }
    
        2
  •  20
  •   William Pietri    16 年前

    我不能让艾德·T的例子发挥作用。也许从那时起圣杯就变了?

    经过一些试验和网络上的搜索,我最终在 UrlMappings.groovy :

        "/"(controller: 'home', action: 'index')
    

    我的家庭控制器如下:

    class HomeController {
    
      def index = {
        def quotes = = latest(Quote.list(), 5)
        ["quotes": quotes, "totalQuotes": Quote.count()]
      }
    
    }
    

    而在 views/home 我有一个 index.gsp 文件。这使得 索引文件 不需要视图中的文件,所以我删除了它。

        3
  •  4
  •   Robert Fischer    16 年前

    好答案是: 如果您需要为索引页填充一个模型,那么是时候从使用直接index.gsp改为使用索引控制器了。

    邪恶的答案: 如果您创建一个控制器为“*”的过滤器,它甚至会对静态页面执行。

        4
  •  0
  •   alk    14 年前

    在Grails 1.3.6中,仅用于添加

    "/index.gsp"(uri:"/")

    对我来说,groovy工作得很好。它与添加新的控制器和映射(如前所述)具有相同的效果。

    以下是我的完整urlmappings.groovy:

    class UrlMappings {
    
        static mappings = {
            "/$controller/$action?/$id?"{
                constraints {
                    // apply constraints here
                }
            }
    
            "/"(view:"/index")
            "500"(view:'/error')
    
            "/index.gsp"(uri:"/")
        }
    }