Making Grails form development DRYer

时光怂恿深爱的人放手 提交于 2019-12-09 06:58:34

问题


When using Grails, the GSP code to render each form field looks something like this:

<tr class="prop">
  <td valign="top" class="name"><label for="username">Login Name:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'username', 'errors')}">
    <input type="text" id="username" name="username" value="${person.username?.encodeAsHTML()}"/>
  </td>
</tr>

<tr class="prop">
  <td valign="top" class="name"><label for="userRealName">Full Name:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'userRealName', 'errors')}">
    <input type="text" id="userRealName" name="userRealName" value="${person.userRealName?.encodeAsHTML()}"/>
  </td>
</tr>

<tr class="prop">
  <td valign="top" class="name"><label for="passwd">Password:</label></td>
  <td valign="top" class="value ${hasErrors(bean: person, field: 'passwd', 'errors')}">
    <input type="password" id="passwd" name="passwd" value="${person.passwd?.encodeAsHTML()}"/>
  </td>
</tr>

Notice that almost exactly the same 5 lines of GSP/HTML code is repeated for each form field. This doesn't seem very DRY to me, and I'm wondering if others have found a better approach?

I've found 2 plugins which attempt to address this problem, the form helper and bean-fields. If anyone has experience using either of these, I'd be very interested to hear from them. Alternatively, if there are other solutions/plugins, please let me know.

Thanks. Don


回答1:


Using the bean-field plugin. Your code will become:

<bean:withBean beanName="person">
    <bean:field property="username" label="Login Name:"/>
    <bean:field property="userRealName" label="Full Name:"/>
    <bean:field property="passwd" label="Password:"/>
</bean:withBean>

Can you find a DRYer solution?




回答2:


For those who read this thread in future - For grails 2.x branch Grails fields plugin is recommended over bean fields, its actually successor of bean-fields and provides flexibility to override default templates




回答3:


Yes, bean-fields plugin is very DRY… your 20 lines can be replaced with one line:

<bean:form beanName="person" properties="username, userRealName, passwd”/>

(Assuming you have i18n properties set)



来源:https://stackoverflow.com/questions/2132796/making-grails-form-development-dryer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!