grails: show list of elements from database in gsp

13,141

Solution 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

Solution 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.

Share:
13,141
FrancescoDS
Author by

FrancescoDS

Curiosity is the key to become a good programmer!

Updated on July 16, 2022

Comments

  • FrancescoDS
    FrancescoDS almost 2 years

    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