Grails - Models and Views



Description

Use the models and views for managing application data and showing the state of data models respectively. You can return the model instance explicitly as shown below:

def info() {
    [team: Team.get(params.id)]
}

You can return an instance of the Spring ModelAndView class, by using the advanced approach as specified below:

import org.springframework.web.servlet.ModelAndView

def index() {
    // defines the team for the index page
    def myTeam = ...

    // further move to players view to display them
    return new ModelAndView("/team/players", [ teamPlayers : myTeam ])
}

The view can be selected by using the info.gsp file present in the grails-app/views folder.

class MycontrollerController {

   def info() { 
      [team: Team.get(params.id)]
	   
      //use the render method to display different view
      render(view: "display", model: map)
   }
}

Rendering a Response

The result of the code or text can be displayed easily by using the rendor method.

render "Welcome..!"

You can display the particular view as:

render(view: 'team')

Even you can display a template for each item in a collection as:

render(template: 'team_template', collection: Team.list())

Display the text along with encoding and content type as:

render(text: "<xml>xml text</xml>", contentType: "text/xml", encoding: "UTF-8")
Advertisements