Making model name human readable in Groovy/Grails

a 夏天 提交于 2019-12-11 12:48:58

问题


Is there a way to make a domain class name human readable in Groovy/Grails? For example, I might have a class called LibraryBook and in the application views, it will be shown as "Create LibraryBook". Is it possible to make Grails show this as "Create Library Book"?


回答1:


If you look at the top of your grails-app/views/libraryBook/create.gsp file, you will see something like:

    <g:set var="entityName" value="${message(code: 'libraryBook.label', default: 'LibraryBook')}" />

This shows you can set a libraryBook.label message property to override the default name of LibraryBook. This property should be set in the grails-app/i18n/message.properties file. The documentation for this can be found here.

As an interesting aside (and not the recommended best practice), you can alter the default grails scaffolding templates. First, you need to install the templates with:

grails install-templates

Then, you can edit the file src/templates/scaffolding/create.gsp (and list.gsp, etc) and change the line:

<g:set var="entityName" value="\${message(code: '${domainClass.propertyName}.label', default: '${className}')}" />

to

<g:set var="entityName" value="\${message(code: '${domainClass.propertyName}.label', default: '${className.replaceAll(/\B[A-Z]/){ " $it" }}')}" />

As you can see, this code:

className.replaceAll(/\B[A-Z]/){ " $it" }

Takes the CamelCase classname, and replaces all capital letters (apart from the first one) with the letter following a space character.

Then when you call generate-views or generate-all, the newly created gsp will have this default name with spaces in it




回答2:


GrailsDomainClass has a naturalName property which you can use. You can also use GrailsNameUtils.getNaturalName() for properties' names.

Still, it's not localizable.

Usual convention is as @tim_yates mentioned, add messages like className.label = Class Name and className.propertyName.label=Property Name to messages.properties.



来源:https://stackoverflow.com/questions/7797566/making-model-name-human-readable-in-groovy-grails

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