收集常见数据(例如侧边栏的数据)的最佳/最干净的方法是什么。在我的应用程序中,我只会有两组不同的数据,具体取决于 User
位于 Project
或不。
我现在正在这样做:
def dashboard = {
def returnVal = getCommonSidebarContent()
returnVal << getCommonHeaderContent()
returnVal << [
//other data related to the main content of this particular page
]
return returnVal
}
getCommonSidebarContent()
之类的将返回用户任务和其他数据的 map 。我知道这很糟糕,它是我开始的,但随着时间的推移,我再也没有时间对它进行分类。
returnVal
开始看起来很乱几乎每个 Controller 方法中的语句。
最佳答案
也许是 filter可以帮你:
class MyFilters {
def filters = {
all(controller: '*', action: '*') {
after = { Map model ->
model.myCommonProperty = ...
}
}
}
}
在过滤器中,您可以在处理请求之前/之后执行通用操作(即向模型添加通用数据)。在
all(controller: '*', action: '*')
内您可以定义应该由过滤器处理的操作(在这种情况下,所有 Controller 中的所有操作都被处理)。另一种方法是使用 beforeInterceptor在 Controller 中。如果您需要在单个 Controller 中执行常见操作,则可以使用它。
关于grails - 收集和渲染公共(public)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16220101/