Grails grailApplication.controllerClasses sort con

2019-08-28 21:50发布

I have the following code that grabs all controllers, sorts it, and outputs in li tags:

<g:each var="c" in="${grailsApplication.controllerClasses.sort { it.fullName } }">
        <li<%= c.logicalPropertyName == controllerName ? ' class="active"' : '' %>>
                <g:link controller="${c.logicalPropertyName}">${c.naturalName}</g:link>
        </li>
</g:each>

I have a need to filter out controllers by package i.e. grab controller from a certain package.

For example:

com.app.module.mars.controller.HelloController
com.app.module.venus.controller.PrintController

As you can see I'm packaging controllers by modules, so mars will have its own set of controllers and venus will have its own. Then in the UI I want to use the above code (with some filter) which will show modules as main-menus and their controllers as dropdowns.

How can I apply such a filter? Or if you could guide me in the right direction would be great. Thanks.

2条回答
姐就是有狂的资本
2楼-- · 2019-08-28 22:29

You can use GrailsClassUtils.isClassBelowPackage() which takes a class and a list of packages as the arguments. So this should do the trick:

GrailsClassUtils.isClassBelowPackage(c.class, ['com.app.module.mars'])

Edit: grailsApplication.controllerClasses probably gives you a list of GrailsClass objects, so you'd want to use c.clazz instead of c.class like

grailsApplication.controllerClasses.each { c ->
    GrailsClassUtils.isClassBelowPackage(c.clazz, ['com.app.module.mars'])
}
查看更多
贪生不怕死
3楼-- · 2019-08-28 22:50

You can use Collection#groupBy to group the controller classes by package name.

I don't have a Grails system to make a quick test right now, but this would be a little example of grouping classes by package name:

def classes = [Integer, List, String]
def classesByPackage = classes.groupBy { it.package.name }
assert classesByPackage == ['java.lang': [Integer, String], 'java.util': [List]]

You can then iterate through each packageName to make each menu and through each class under that package name to make each menu item. Something like...

classesByPackage.each { packageName, packageClasses ->
    println "Menu $packageName"
    packageClasses.each { println "  Item $it.simpleName" }
}

... but with GSP-style loops :)

查看更多
登录 后发表回答