grails - 如何避免GSP中的常规代码?

标签 grails gsp

我必须基于多于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/

相关文章:

hibernate - Grails 将多对一从集合更改为列表(列需要更改)

grails - CountBy WithCriteria不匹配

grails - ils。在控制台上执行命令

grails - 在Grails中渲染HTML文件

Grails - 分隔字符串的多个复选框

grails - 如何将数据从一个grails应用程序发送到另一grails应用程序

grails - 在gsp文件中添加条件

grails - Grails-g:textField在Firefox中创建两个自动填充结果

Grails:从流范围检索bean