【发布时间】:2013-04-15 20:55:01
【问题描述】:
我必须根据一些超过 4 行 groovy 代码的逻辑来显示复选框是否选中... 我不喜欢在 GSP 页面中写它。有没有任何 taglib 或某种方法可以从 GSP 页面中提取逻辑。 我可以在其中访问模型对象和请求对象。
【问题讨论】:
我必须根据一些超过 4 行 groovy 代码的逻辑来显示复选框是否选中... 我不喜欢在 GSP 页面中写它。有没有任何 taglib 或某种方法可以从 GSP 页面中提取逻辑。 我可以在其中访问模型对象和请求对象。
【问题讨论】:
你有(至少)3个选项:
模型属性
如果你只是为单个页面或单个控制器做复杂的逻辑,在控制器方法中做逻辑,并通过布尔值将布尔结果传递给视图:
// in your controller
def myAction() {
[shouldDrawCheckbox: shouldDrawCheckBox(...)]
}
private boolean shouldDrawCheckBox(/* info for decision making */) {
// decision making
}
服务方式
如果您要从多个控制器访问相同的逻辑,您可以将shouldDrawCheckBox 方法提取到服务中,然后再次将结果传递给模型。
class MyController {
def myService
def myAction() {
[shouldDrawCheckbox: myService.shouldDrawCheckbox(...)]
}
}
class MyService {
boolean shouldDrawCheckBox(...) {
// logic!
}
}
自定义标签库
如果您想避免通过模型传递决策,或者如果逻辑更普遍适用,您可以创建自定义标记库。
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="..."/>
【讨论】:
TagLib 是放置逻辑的好地方,您可以将所需的内容作为属性传递并进行测试:
class MyTagLib {
static namespace = "my"
def somecheckbox= { attrs ->
def model = attrs.remove('model')
if() { //tests goes here
//you can also test if you need to mark the checkbox as checked
if() {
attrs.checked = "checked"
}
out << g.checkbox(attrs: attrs) //remaining attrs will be applied to the checkbox
}
}
}
myview.gsp
<my:somecheckbox model="${model}" name="checkboxname" value="${checkboxValue}" />
【讨论】:
理想情况下,逻辑应该转到renders gsp 的控制器,并在model 对象中设置一个标志。如果 gsp 是模板的子级,则标志必须通过。当我们在 grails 中有适当的绑定框架时,视图层中的 DOM 操作并不理想。
【讨论】:
使用g: 命名空间。 http://grails.org/doc/2.2.x/ref/Tags/checkBox.html
<g:checkBox name="myCheckbox" value="${condition}" />
没有比这更简单的了。所有的逻辑都应该在控制器内部完成。
您在页面上需要的所有数据都可以由控制器传递。只需返回 Map。
class MyController {
def index() {
def someCondition = true
[request:request, condition:someCondition]
}
}
【讨论】:
value怎么能被上面示例代码前面提到的“4行Groovy代码”动态处理呢?提前感谢您的解释。
edit 的内容,我猜这未被接受。感谢最新的编辑使示例代码清楚地了解condition 的用法。