How to partially update a layout / template in Grails - templates

I'm not really experienced with web development especially on views , I need a simple explanation (and pointers to a resource would be really nice as well) on how to deal with rendering a layout or a template partially without rendering whole page again...
What is the best practice?
Does Sitemesh layouts provide this? if so how ?
Shall I use JQuery pass the data as JSON from controller and update the corresponding div with ".html()" ? (which i did something like this a long time ago for some basic stuff, and think this is not really a grails way to do it)
or <g:include> does this for me?
Everything I read about this confused me even more :)
Actually the question is, what is the best practice in Grails to handle partial page updates (with Ajax or without ajax if there is any other ways these days)
Thanks in advance
EDIT:
this tutorial actually gives a really good idea of how to do it

What is the best practice?
The usual practice is to submit an AJAX request (i.e. a HTTP request triggered from JavaScript), and use a JavaScript callback function that updates a section of the page when a response is returned.
Does Sitemesh layouts provide this? if so how ?
When an AJAX request is received on the server-side, you could layout the response using Sitemesh in the same way that you can layout the response of a non-AJAX request. Sitemesh doesn't know or care what kind of request is being processed or whether it's laying out a whole page or just a fragment.
Shall I use JQuery pass the data as JSON from controller and update the corresponding div with ".html()"
Have a look at the tags provided by Grails that have the word "remote" somewhere in the tag name. They provide a very simple way to perform common AJAX tasks within a Grails application. For example, to submit an AJAX request to an action named bookByName and add the response to an element with id foo, simply add the following tag to your page.
<g:remoteFunction action='bookByName' update='foo'/>

Probably you need to use RemoteLink tag: http://grails.org/doc/latest/ref/Tags/remoteLink.html
You can configure it to update some fragment of your page, after calling an remote action.
BTW, it's grails way too, to use ajax and javascript, on client side :)

Related

Django: Is there any performance differences when using ajax?

I'm working on refactoring project in the middle of the work. There are a lot of context when view return render. I want to change it to get response when dom rendered using ajax.
I know it makes more request, but I wondered if there are any performance differences. If not, I want to do that.
According to my understanding, using AJAX and context are completely different methods.
AJAX does things on the client-side, while the Django context works on the server.
According to this basic difference, and considering the size of your page is large and multiple time changes, the AJAX is faster because you will only be requesting the data and not the whole page
But
If we assume the size of your page is large but data don't change frequently, the Django-Context is better in the scope of security and usability, because you will not expose the data that is to be rendered as it will be if used AJAX.
So it depends on your use case, if it's a static page then it is better to use django-context than AJAX and if it's a dynamic page use AJAX.

What does django controllers are in views.py

I have followed several django tutorials. I do not know why controllers are stored in a file called views.py. I am confuse with this filename. I am looking for a MVC development. Are there other files in django for "real" controllers ?
The name views.py was a mistake
From an architecture point of view, it was a mistake to call views.py the module where functions receive an HTTP request and produce an HTTP response.
Such module is clearly a controller in the MVC sense. (For comparison, the equivalent functionality in the Spring framework is in a class with annotation #RestController or #Controller.)
Such module is also a REST adapter if you use the Ports & Adapter architecture style (aka Hexagonal architecture).
Such module deals with in-out data (request-response), but it is not a representation of the view displayed to the user. If not, what about an http DELETE endpoint (#api_view(['DELETE']))? What about an http POST endpoint that triggers background processing and has no bearing on what the Web UI shows? The functions in views.py are "handlers" of user actions (i.e., controller in MVC), not the representation of UI data.
I understand that views.py is a convention and you can use other names, but once the tutorial examples and other documentation use that name, it sticks.
Another mistake is when tutorials like this use the name views.py as the single place for all http endpoints. The name views.py is too generic and its very idea is an invitation to violate the Single Responsibility Principle (SRP).
Even simple tutorial examples, should use better names. For example:
if you're handling endpoints that deal with customer functionality, call it views_customer.py or customer_views.py (or better yet, customer_controller.py if you're bold to break with the convention and call it for what it is).
Yes ! Actually it's a design decision and It's described by the guys behind Django Here.
Basically their argument is that, in their opinion,
In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction.
a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.
I entice you to read the entry to get a hold of the overal idea behind the views naming.
About the controllers, Yes again. Mostly though, you can define several layers of the so called Middlewares in django to handle lots of your static logic before/after requests are handled by views, but still, it's the view that plays the main role of a controller in Django.
Look at this logically. What do you normally call a text file with placeholders which is filled with other bits of text by supplying variables? You call that a "template", you don't call that a "view". Only in MVC would you think of calling such a thing a "view".

Ember-Data: Adding Server Queries to AJAX Requests

I am having trouble with a specific case using Ember-Data.
Typically Ember expects a model class, the route, the ajax request, and the returned JSON, to all follow a similar pattern.
The RESTAdapter tries to automatically build a URL to send to the server, which is ok for some situations, but I need full control over some of my request URLs particularly when it comes to appending additional parameters, or matching an API to a route that has a completely different URL structure.
Ember sadly, has no guides for this, though I did find something about the buildURL method
I am not comfortable enough rooting through the source code to find out what happens under the hood though I do not want to break ember data just to fix a few use cases.
I have set my RESTAdapter's namespace to api/rest
The model and resource I want to populate is view-debtors
The specific service I want to reach is at debtor/list
I also need to pass extra parameters for pagination ?page_size=10&page_number=1, for example.
I am completely lost how to do this. I cannot change the API structure... there are too many services depending on them.
Some Small Progress
I went ahead and used my current knowledge to get a little closer to the solution.
I created a model and called it "list"
I extended RESTAdapter for "list" to change the namespace to "api/rest/debtor"
I changed the model hook for "view-debtors" route to store.find('list')
The result now is that the AJAX call is almost correct... I just need to add those extra parameters to the server queries.
This is where I stand now... can I add those server queries via the model hook? or better yet can I also control server queries via ember actions to get new AJAX requests?
Stepping back a bit. Is my method so far a good practice? Because I am using a route's model hook, to set the model to list, will this only work if the routes URL is typed in directly?
So many questions :p
You can find by query which will append a query string onto the end of your request using the object provided.
// this would produce /api/rest/debtor/lists?page_size=1&page_number=10
this.store.find('list', {page_size:1, page_number:10});
Personally I think it's a bit hacky to go fudging the model names and namespace to make it supposedly fit your backend's url structure. It really depends on what you're attempting to do. If you want all the full features of CRUD using Ember-Data for this particular list of data, you're going to be hacking the end-point left and right. Whether or not Ember Data really helps you is questionable. If you are just reading data, I'd totally just fetch the data using jquery and sideload it into Ember Data.
var store = this.store;
$.getJSON('/api/rest/debtor/lists?page_size=1&page_number=10').then(function(json){
//fix payload up if necessary http://emberjs.com/api/data/classes/DS.Store.html#method_pushPayload
store.pushPayload('type', json);
}).then(function(){
return store.all('type'); // or store.filter('type') if you want to filter what is returned to the model hook
});
pushPayload docs

CFWheels - Multi-step form?

I am wondering how one would setup a multi-step form in CFWheels.
Clearly I would need to store form data in the session etc as I go, but I would like to know the best approach from a wheels perspective to do this the 'wheels way'.
Do I have just one action in my controller that handles this? Or would it be best to seperate each part of the form out into separate actions?
Advise on this and possible code examples would be much appreciated.
Thanks,
Michael
The way I've done it in past is use Ajax calls and a jquery modal.
though the jquery modal is not important, I just like the aesthetic. a simple div replacement will also work.
If you cannot be sure that the users can use AJAX then it won't work for you, but you might be able to use a popup window.
The advantage of using Ajax calls for multi-step forms is that you can adjust the form content from one step to another. Another advantage is that you don't have to store user data in the cache or session. Because each time you send a form, you can use the POST or GET.
For this to work, the quickest way of setting this up is to use the plugin called RemoteFormHelpers. Then each step of the form would be a different controller (or the same one with a switch statement based on the data passed)
I think this is a pretty versatile way of doing this, but you cannot do a form that uses file-uploads, well not easily as ajax won't let you do it without some serious pain.

Who should format my data for display?

I have a django view, and this view returns a table which is populated asynchronously with an ajax call.
From the design point of view, which one should I follow:
the django view, called via ajax, returns the content of the table as a json response, containing html markups for each cell. The javascript callback handler takes the contents and slaps them untouched into the table cells.
the django view, called via ajax, returns pure data about what should go into the table, again as a json response. The async javascript callback takes the data, formats them with proper markup, and puts it into the table.
In other words, who should have the responsibility for markup formatting of the cell contents? the view or the javascript ?
I would be tempted to say the first, since the view already returns marked up content. If it returns a json containing marked-up content, there's not much difference.
I would like to hear your point of view.
If you're populating the whole table, you can put your table in its own template and return the table's html via ajax/json.
You'll need to edit the original template to include the table template:
{% include "myapp/_table.html" %}
And in the view, return the rendered template as a json variable, which your javascript will substitute in:
return { 'table': render_to_string("myapp/_table.html", context) }
This approach is good where you always want to update the entire table, and the rendering of the table doesn't require the full context. I'm not sure what the performance is like, but it is a clean way of updating part of the page, because you only define your table once.
It depends (as so often).
If the data is requested only here and now, it would be easier and less error prone to just let it render on server-side with the same set of templates that already rendered the standard view.
If you could think of use cases however, where the data would be needed in other places (like auto-complete fields), it would be better to let JavaScript do the job and create a clean, reusable JSON export.
These options add to all the other answers, and finally it's up to you to decide.
In a MVP system such as Django, the View decides what data should be shown, and the Presenter decides how it should be shown. Therefore the JavaScript should do the bulk of the formatting unless it proves intractably difficult to do so.
It is a good to practice Unabstrusive javascript, also called by some people as Hijax
So, you first have a standard page, that presents the table along with the rest of the page, with table in a particular django-template block.
Once you have this, you can include the extends part of the django template within an "if not ajax", so you only get the required table part in the ajax response which you can load in the client to the required div.
It is un-necessary and redundant to maintain the markup twice once at the server and once at the client, in javascript.
hence, I'd prefer the first option, of server redering, and client only loading the rendered html.
I've come across this several times before, and I generally opt for the latter, where the view returns pure JSON.
However, the approach you choose should definitely depend on several factors, one of which is targeted devices (and their CPU/network constraints). Pure JSON will generally result in smaller payloads and so may be optimal for mobile devices.
It may also make sense to expose both HTML and JSON versions of your content. This is especially helpful if you're looking to create a very lightweight API at some point for your site.
Finally, you can use a library such as John Resig's micro-templating or Closure Templates to simplify client-side HTML generation.
I would go with first choice, sine it presents more pros for user: page loads instantly (no wait for async call), no JS required (e.g. for mobile device)