Search code examples
grailscontrollernullviewdata

Grails Controller data passed to view is null when accessed on view?


I have an application that has some controllers, views and layouts. I am basically trying to pass some data from the Controller to the view. The view in question uses a layout called main.gsp in the layouts folder. So I used the code below in order to try and passed the data to the view:

def index = {

        String test = "Testing"
                println(test)
        render(view:"index", name: test)
    }

Then on the view it looks like this:

<html>

<head>
    <title>My App</title>
    <meta name="layout" content="main" />
</head>

<body>

        <h1>${name}</h1>
.......

Then when I run the application I can see the print data is fine however there is no data being passed to the view, is this because there is a layout being used? if so how to I get round this? Do I access a meta object instead? Thanks in advance :-)


Solution

  • Try this:

    def index = {
        String test = "Testing"
        println(test)
        [name: test]
    }
    

    This will render your index view by convention.

    From your controller you have to pass a the model (map) to your view.

    Now you could use the elements of the returned map within your view:

    <h1>${name}</h1>
    

    See the docs for further informations.