Rasmus
Rasmus

Reputation: 8486

Python Templating and Ajax

I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.

I am using flask as my python framework, and normally I render templates doing somnething like the below:-

@app.route('/home')
def userhome():
    data=go get user details from the database
    return render_template("home.html",userdata=data)

Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.

However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript). The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.

I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.

Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.

Upvotes: 1

Views: 692

Answers (2)

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17516

I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.

In the home.html template, I'd do something like

<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>

And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375634

You have two options: template on the server, or template in the browser.

To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.

To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example.

Upvotes: 3

Related Questions