grails: show list of elements from database in gsp

北城余情 提交于 2019-12-07 13:53:23

问题


in my grails app I need to get some data from database and show it in a gsp page. I know that I need to get data from controller, for example

List<Event> todayEvents = Event.findAllByStartTime(today)

gets all Event with date today Now, how can I render it in a gsp page?How can I pass that list of Event objects to gsp?

Thanks a lot


回答1:


You can learn many of the basic concepts using Grails scaffolding. Create a new project with a domain and issue command generate-all com.sample.MyDomain it will generate you a controller and a view.

To answer your question create a action in a controller like this:

class EventController {

    //Helpful when controller actions are exposed as REST service.     
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def showEvents() {
        List<Event> todayEvents = Event.findAllByStartTime(today)
        [eventsList:todayEvents] 
    } 
}

On your GSP you can loop through the list and print them as you wish

<g:each in="${eventsList}" var="p">
 <li>${p}</li>
</g:each>

Good luck




回答2:


I am not sure if this is really what you meant, because in that case I suggest you to read some more on the grails :), but anyway, for your case you can use render, redirect as well but here I am taking simplest way:

In your controller you have:

def getAllElements(){
    List<Event> todayEvents = Event.findAllByStartTime(today)
    [todayEvents :todayEvents ]
}

and then in the GSP(I assume you know about grails conventions, as if you don't specify view name, it will by default render gsp page with the same name as the function in the controller, inside views/):

<g:each in="${todayEvents}" var="eventInstance">
    ${eventInstance.<propertyName>}
</g:each>

something like this.



来源:https://stackoverflow.com/questions/17426953/grails-show-list-of-elements-from-database-in-gsp

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