Implementing Django Templates and jQuery Templates Together - ajax

I'm working on a website that uses AJAX to retrieve data from the server and display it on the page. Django renders the initial page content using its template engine (so it will be indexed by search engines). When the user takes an action, jQuery fetches the new data via AJAX and the response is returned as JSON. I would like to have jQuery render this new content without violating the DRY Principle. Therefore I would like to use a templating engine that is "shared" between Django and jQuery. I've been running in circles trying to find the best solution but always seem to run into a road block.
Has this already been done? Here are the options I have thought of:
Use regular expressions to transform the Django template into correct jQuery template syntax, and render it in its raw form to the page. jQuery will then pick it up and use it to render the new data.
Extend the jQuery template engine to recognize the Django template syntax, again rendering the raw Django template to the page for jQuery to use.
Has this been successfully done before? Either way seems like a lot of work for anything but the simplest of Django templates because of the plethora of Django tags and filters that would need accounted for.

Your best bet is to pick a template language that has both Javascript and Python support, and use that everywhere.
As far as I know, Mustache is your best bet.

I haven't found a perfect solution since I asked this question, but for the sake of development time I resorted to sending back both JSON and HTML in the AJAX response. This way the django templates still perform the HTML generation, but javascript is still free to utilize the data without having to parse the HTML.
I am sending approximately twice the data over the network, but I'm going to live with it until my application grows to the point where a smaller response is beneficial. At that point I will probably look into something like Mustache as Rob mentioned.

Related

Share templates between Laravel and JavaScript

How do I share template information between my PHP backend and JavaScript / AJAX requests?
Times ago I just sent my AJAX requests and had the HTML generated by the server and sent as such. Today I have my AJAX data as JSON but I have no idea how to use the same template (e.g. a users list) at the server side and (for refreshing, filtering etc.) at client side without creating redundant layout code.
Is there a template language with parsers as well for PHP/Laravel and JavaScript?
The Laravel template engine Blade is obviously not usable in JavaScript.
The only sharing template language I found via Google was Mustache, but the parser for Laravel was outdated.
Is there anything else out there and which approach do you use for that?
Your boiled down question:
Is there a template language with parsers as well for PHP/Laravel and
JavaScript?
Laravel and Mustache | server side:
conarwelsh/mustache-l4 is a Mustache.php wrapper for Laravel 4. They seems to keep up very well as opposed to what you tell (I presume you mean michaelenger/mustacheview which is actually a Laravel 3 bundle). I stand corrected if am wrong.
Laravel's Blade doesn't rule out Mustache at all. You just have to create a Mustache partial without using blade.php extension and include it within a regular Blade template using #include (More details here)
Serving Mustache template:
You can even coin any custom Response you need using Response Macros such Response::mustache(...) leveraging Response::make(...) (see here for more details).
Some samples of interest:
Combining Laravel 4 and Backbone.
Sharing Templates Between PHP and JavaScript | PHP but still relevant!
My short answer (Updated):
Don't look elsewhere: Laravel + Mustache + Javascript if a mix of server|client side rendering is part of your requirements.
Get your hands dirty! :)
I had the same issue with Laravel and Angularjs, what I did is that I created a route to return templates http://domain.com/templates/name
This route will View::make('templates'.$name);, this is an AngularJs template that will be filled with data returned by JSON API. Remember to use non conflicting tags I used {{ for Laravel and <% for Angular.
RENDER YOUR TEMPLATE SERVER SIDE! I'm not sure at what point someone decided you needed to send JSON to the front end, but that's not how they do it in Rails. In Rails, they actually render the template server side, then send it back to the front end and your JS appends it to the page (or, actually sends back the JS + the markup to attach). This saves a ton of time and headache, trust me.

How to change only a part of web page? (is there a non JS solution?)

Hi I'm pretty new to web applications, and I want to make a small form that search for an object and show the results there. I don't want to load the whole web page, probably change only one <div> tag.
Is there a way to do this without Javascript? (It's not mandatory that I don't. Just checking if I can)
I'm using Pyramid framework (and has been working with less than 2-3 days, so please be patient with your answers).
Please point me in the right direction, I feel like I don't even know what to search for.
(Didn't go anywhere with my pyramid XMLHTTPRequest google search).
Thanks a bunch.
No, that's what AJAX is, a Javascript technique. You cannot initiate a XMLHTTPRequest from your browser without it.
Just use jQuery to load a URL from you Pyramid server; have one route serve up a HTML snippet instead of a full page:
$('div#somediv').load('http://serveraddress/route/to/snippet')
and jQuery will request /route/to/snippet from your server, and place the result wholesale under <div id="somediv"></div>.
What you need is a Javascript library like jQuery to do the XMLHTTPRequest (popularly known as AJAX). See jQuery.post()

Is there a way in CakePHP to partially re-render a view on the server-side when requesting data asynchronously?

I'm planning on experimenting a bit with the HTML5 History API on my website to asynchronously render new content and save states for the browsers that support it. Obviously this means making a lot of AJAX requests to the server, and I've hit a snag in terms of design approach. I've some areas on the site that already render content asynchronously in small ways, and in those places I've just been rolling my own solutions to generate the new HTML on the client side.
However, what I'm trying to do now will require a bit more of a robust solution, and I'd like to do it in a way that takes advantage of the MVC flow rather than relying on a javascript templating engine or my own whacky javascript to handle the raw data returned by my controllers. Since this feature will only be relevant to certain HTML5 capable browsers, I'd rather not introduce a lot of extra bloat on the client side for something a lot of people may not even see.
Essentially, what I'm wondering is: is there a way in Cake to take advantage of the presentation logic that's already in my view files to selectively generate and return just the new, ready-to-go HTML that I need instead of reinventing the wheel to do it on the client side from raw data returned by the controller?
I don't really get your problem but i sounds like you want to cache the view which is in fact rendered by a view class but send back to the browser through the controller by using the CakeResponse object.
Caching: http://book.cakephp.org/2.0/en/core-libraries/caching.html
Response: http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse

Ajax architecture in Django application

I am trying to find the optimal architecture for an ajax-heavy Django application I'm currently building. I'd like to keep a consistent way of doing forms, validation, fetching data, JSON message format but find it exceedingly hard to find a solution that can be used consistently.
Can someone point me in the right direction or share their view on best practice?
I make everything as normal views which display normally in the browser. That includes all the replies to AJAX requests (sub pages).
When I want to make bits of the site more dynamic I then use jQuery to do the AJAX, or in this case AJAH and just load the contents of one of the divs in the sub page into the requesting page.
This technique works really well - it is very easy to debug the sub pages as they are just normal pages, and jQuery makes your life very easy using these as part of an AJA[XH]ed page.
For all the answers to this, I can't believe no one's mentioned django-piston yet. It's mainly promoted for use in building REST APIs, but it can output JSON (which jQuery, among others, can consume) and works just like views in that you can do anything with a request, making it a great option for implementing AJAX interactions (or AJAJ [JSON], AJAH, etc whatever). It also supports form validation.
I can't think of any standard way to insert ajax into a Django application, but you can have a look to this tutorial.
You will also find more details on django's page about Ajax
Two weeks ago I made a write up how I implement sub-templates to use them in "normal" and "ajax" request (for Django it is the same). Maybe it is helpful for you.
+1 to Nick for pages displaying normally in the browser. That seems to be the best starting point.
The problem with the simplest AJAX approaches, such as Nick and vikingosegundo propose, is that you'll have to rely on the innerHTML property in your Javascript. This is the only way to dump the new HTML sent in the JSON. Some would consider this a Bad Thing.
Unfortunately I'm not aware of a standard way to replicate the display of forms using Javascript that matches the Django rendering. My approach (that I'm still working on) is to subclass the Django Form class so it outputs bits of Javascript along with the HTML from as_p() etc. These then replicate the form my manipulating the DOM.
From experience I know that managing an application where you generate the HTML on the server side and just "insert" it into your pages, becomes a nightmare. It is also impossible to test using the Django test framework. If you're using Selenium or a similar tool, it's ok, but you need to wait for the ajax request to go return so you need tons of sleeps in your test script, which may slow down your test suite.
If the purpose of using the Ajax technique is to create a good user interface, I would recommend going all in, like the GMail interface, and doing everything in the browser with JavaScript. I have written several apps like this using nothing but jQuery, state machines for managing UI state and JSON with ReST on the backend. Django, IMHO, is a perfect match for the backend in this case. There are even third party software for generating a ReST-interface to your models, which I've never used myself, but as far as I know they are great at the simple things, but you of course still need to do your own business logic.
With this approach, you do run into the problem of duplicating code in the JS and in your backend, such as form handling, validation, etc. I have been thinking about solving this with generating structured information about the forms and validation logic which I can use in JS. This could be compiled at deploy-time and be loaded as any other JS file.
Also, avoid XML. The browsers are slow at parsing it, it is a pain to generate and a pain to work with in the browser. Use JSON.
Im currently testing:
jQuery & backbone.js client-side
django-piston (intermediate layer)
Will write later my findings on my blog http://blog.sserrano.com

Listing ajax data in search engines?

Is there any way to allow search engines to list JSON or XML ajax data ?
I don't think there is a way to directly allow crawlers to index XML and JSON.
I would recommend trying to design your site using progressive enhancement. First, make all of the JSON and XML available in HTML form for users who don't use javascript. These users include some people with disabilities and the crawlers used by search engines. That will ensure your content is searchable.
Once you have that working and tested, add your ajax functionality. You might do this by serving HTML, XML and JSON from a single URL using content negotiation, or you might have seperate URLs.
Another graceful solution is to implement your ajax calls as requests to full HTML pages and have your javascript only use the bit that it's interested in e.g. a div with id "content. The suitability of this solution would depend on your exact requirements.
Hmm, no, not really. Search engines crawl your HTML and they don't really bother clicking around or even just loading your page into a browser and having the AJAX magic happen. Flash and JSON objects are by themselves invisible to search engines, and to get them visible, you have to transform them in some HTML.
The newest technique for getting AJAX requests to be listed in search engines is to ensure they have their own URL. This technique stems from the same one utilized by flash applications where each page has a unique identifier, preceded by a pound (#) sign.
There are currently a few jQuery plugins which will allow you to manage this:
SWFAddress - Deep Linking for Flash & AJAX
jQuery History Plugin

Resources