grails索引页面的最佳实践

dan*_*anb 27 indexing grails model

在grails应用程序中为索引页填充模型的正确方法是什么?默认情况下没有IndexController,是否有其他机制可以将此列表及其中的列表添加到模型中?

Ed.*_*d.T 36

我不会声称这是正确的方法,但它是开始一切的一种方式.将控制器作为默认值并不需要太多.添加映射到UrlMappings.groovy:

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

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

class QuoteController {

    def index = {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

def index = {
    redirect(action: random)
}
Run Code Online (Sandbox Code Playgroud)

或者真正得到一些重用,将逻辑放在服务中:

class QuoteController {

    def quoteService

    def index = {
        redirect(action: random)
    }

    def random = {
        def randomQuote = quoteService.getRandomQuote()
        [ quote : randomQuote ]
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为UrlMappings应该读成"/"{controller:"quote"}`.在我将"="更改为":"之前,它对我不起作用. (2认同)

Wil*_*tri 21

我无法让Ed T的例子在上面工作.也许Grails从那时起发生了变化?

经过一些实验和网上的一些搜索,我最终得到了UrlMappings.groovy:

    "/"(controller: 'home', action: 'index')
Run Code Online (Sandbox Code Playgroud)

我的HomeController看起来像这样:

class HomeController {

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

}
Run Code Online (Sandbox Code Playgroud)

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