Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Grails compose responses?

The folks over at LinkedIn have been using Play in an interesting way to handle pages that need to be composed of many different components: http://engineering.linkedin.com/play/composable-and-streamable-play-apps

The critical component of how they are doing it is the fact that "actions" in Play return full responses and so are able to be "composed" into another response by a higher-level action.

Grails doesn't seem to really return anything from actions (or at least nothing specific), and there isn't an easy way to call another action when you are inside one.

So, is this style of composing responses possible with Grails?

like image 644
cdeszaq Avatar asked Nov 11 '22 14:11

cdeszaq


1 Answers

I watched the video, awesome stuff.

I can't think of any way to compose responses sticking strictly to Grails features (you said it well, there's no easy way to call an action from another action), but you may obtain some of the benefits shown in the presentation combining Grails controllers template rendering with Ajax calls (yes, this is clearly just a workaround).

Anyway, I'd set up a home.gsp defining the main layout:

<html>
<head></head>
<body>
    <div><h1>Title</h1></div>
    <div id="section1"></div>
    <div id="section2"></div>
</body>

Then add some Ajax:

$(document).ready(function(){
    $.ajax({
        type: "POST",
        url: "${g.createLink(controller: 'home', action: 'section1')}",
        dataType: "html",
        success: function (data){
            $('#section1').html(data);
        }
    });
    $.ajax({
        type: "POST",
        url: "${g.createLink(controller: 'home', action: 'section2')}",
        dataType: "html",
        success: function (data){
            $('#section2').html(data);
        }
    });
});

HomeController would look like this:

...
def section1() {
    // Some code to fetch cool data...
    render template: 'section1', model: data
}
def section2() {
    // Some code to fetch cool data...
    render template: 'section2', model: data
}
...

(I omit the templates _section1.gsp and _section2.gsp.)

As soon as the ajax calls return the data, the templates are rendered in the page. Also, sections are independent, meaning you can edit section1 content and layout without bothering about section2.

Just to try this out, I made a small (and ugly enough, didn't have much time) grails application (https://github.com/nicosalvato/tochi).

This said, maybe your question was more theoretical (a "how Grails deals with functional programming" kind of question ) than practical. Feel free to call me an idiot if I totally missed the point :)

like image 62
nicosalvato Avatar answered Nov 26 '22 19:11

nicosalvato