I’d like to know more about customising grails controller generationg but I can’t find any documentation.
Specifically my motivation is that I’m working with a legacy database and this is readonly. So I’d like to customise the code generation such that if a domain class is in a certain package eg: toppackage.readonly then only read only code is generated, only the list and show methods on controllers.
I’ve played around a bit with it and I’m not sure exactly how they are parsing the templates. They contain <%%> tags and seem sensitive to semantic white space.
I know the design intentions for scaffolding were to give you a starting point, but it is often the case that something is revisited later and changed and regenerating things again seems wasteful. There also are bound to be conventions that are specific to a project which belong in the code generation phase. In our case there are some security requirements that belong in the code generation phase.
How do I inject variable into the code template?
How do the tags get evaluated? is it a form of OGNL ?
I put in some horrible ugly way to do this for now, by putting domain classes in a package with readonly in the name and this in controller template:
<%=!(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
}
}""" : ''%>
The following should work:
execute
grails install-templatesto install the templates and modify them (http://grails.org/doc/1.3.7/ref/Command%20Line/install-templates.html)You don’t have to add
\nor escape",${..}unless if you want to generate those things into your result (like the message).To make it short:
<% .. %>gets printed into the result<% .. %>gets evaluated during scaffolding${..}get resolved when outside the<% .. %><% .. %>, no${..}needed\${..})