我必须基于多于4行的groovy代码的某些逻辑来显示复选框是否已选中...
我不喜欢在GSP页面中编写它。是否有任何taglib或某种方式可以从GSP页面中提取逻辑。
在这里我可以访问模型对象并请求对象。
最佳答案
您(至少)有3个选择:
模型属性
如果只对单个页面或单个 Controller 执行复杂的逻辑,请在controller方法中执行逻辑,然后通过 bool(boolean) 将 bool(boolean) 结果传递给 View :
// in your controller
def myAction() {
[shouldDrawCheckbox: shouldDrawCheckBox(...)]
}
private boolean shouldDrawCheckBox(/* info for decision making */) {
// decision making
}
服务方法
如果要从多个 Controller 访问相同的逻辑,则可以将
shouldDrawCheckBox
方法提取到服务中,然后再次将结果传递给模型。class MyController {
def myService
def myAction() {
[shouldDrawCheckbox: myService.shouldDrawCheckbox(...)]
}
}
class MyService {
boolean shouldDrawCheckBox(...) {
// logic!
}
}
自定义Taglib
如果要避免通过模型传递决策,或者如果逻辑更通用,则可以创建自定义标记库。
class MyTaglib {
static namespace = "my"
def myCheckbox = { attrs ->
// extract decision info from the attrs
// perform logic with info
if (shouldDrawCheckbox)
out << g.checkbox(attrs: attrs)
}
}
}
您认为:
<my:myCheckbox whateverYourAttribsAre="value" name="..." value="..."/>
关于grails - 如何避免GSP中的常规代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024553/