我想了解更多有关自定义grails控制器generationg的信息,但我找不到任何文档。
具体来说,我的动机是我正在使用遗留数据库,这只是一个只读。所以我想自定义代码生成,这样如果一个域类在某个包中,例如:toppackage.readonly那么只生成只读代码,只有控制器上的列表和show方法。
我玩了很多,我不确定他们是如何解析模板的。它们包含< %%>标签,似乎对语义空白区域很敏感。
我知道脚手架的设计意图是为你提供一个起点,但通常情况下,某些东西会在以后被重新访问并且改变并再次重新生成东西似乎是浪费。还必须存在特定于属于代码生成阶段的项目的约定。在我们的例子中,有一些安全要求属于代码生成阶段。
如何将变量注入代码模板?
如何评估标签?它是OGNL的一种形式吗?
我现在做了一些可怕的丑陋方法,通过将域类放在一个名为readonly的包中,并将其放在控制器模板中:
<%=!(packageName=~/\readonly/) ? """ def save = {\n
def ${propertyName} = new ${className}(params)\n
if (${propertyName}.save(flush: true)) {\n
flash.message = \"\${message(code: 'default.created.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), ${propertyName}.id])}\"\n
redirect(action: \"show\", id: ${propertyName}.id)\n
}\n
else {\n
render(view: \"create\", model: [${propertyName}: ${propertyName}])\n
}
}""" : ''%>
答案 0 :(得分:2)
以下内容应该有效:
执行grails install-templates
安装模板并对其进行修改(http://grails.org/doc/1.3.7/ref/Command%20Line/install-templates.html)
<% if (!packageName.contains("readonly")) { %>
def save = {
def ${propertyName} = new ${className}(params)
if (${propertyName}.save(flush: true)) {
flash.message = "\${message(code: 'default.created.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), ${propertyName}.id])}"
redirect(action: "show", id: ${propertyName}.id)
}
else {
render(view: "create", model: [${propertyName}: ${propertyName}])
}
}
<% } %>
除非您想在结果中生成这些内容(例如消息),否则您不必添加\n
或转义"
,${..}
。
简而言之:
<% .. %>
以外的所有内容都会打印到结果中<% .. %>
内的所有内容都会在脚手架中进行评估${..}
<% .. %>
中的所有变量都会得到解决
<% .. %>
内部解决,而不需要${..}
\${..}
)