Reusing loops in django templates
I was wondering if there's a way to repeat a loop with new objects gathered through jquery/ajax, for example i have {% for car in cars %}
do something, then after getting new car objects through an ajax call I w开发者_运维知识库ant to discard the current objects and display the new objects using the same loop. Is that possible? This is for implementing a search function, I initially show some objects but I have a search box for people to find specific objects. I thought of returning ready made html and replacing the html directly but that's a bit annoying.
The best approach (I think) for doing this, is:
have a view set up in Django, such as
view_cars
that outputs the result page based on a regularGET
request. The URL for this might look likehttp://mysite.com/cars/1
. The template for that view might look like this:<div id="cars"> {% for car in cars %} <!-- output here! --> {% endfor %} </div>
have jQuery load the results with the
$.load()
function, like so:$("#cars").load("http://mysite.com/cars/2 #cars");
The search results will be automatically loaded into the #cars
div, and you don't have to handle the special AJAX case within Django.
Once the template has gone through the template engine there are no more loops, just text output in one form or another. But when you use AJAX it re-enters the top of the/a view, so you can reuse any loops you like at that point.
精彩评论