问题
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