samedi 29 novembre 2014

Django : Restitue un modèle en bloc sans charger la page entière - Stack Overflow


I have a short question and i am sure there is a simply answer. I have a template called base.html which looks simplified like this:


<html>
<head>
<title>{% block title %} Title {% endblock %}</title>
</head>
<body>
<div class="header">
{% block header %}My Header{% endblock %}
</div>

<div class="navigation">
{% block navigation %}My Navi{% endblock %}
</div>

<div class="content">
{% block content %}Content{% endblock %}
</div>
</body>
</html>

When i click on a link in the navi i want to render the new content in the content block without loading the header and die navigation again.


Thanks




You have a couple of choices: Ajax or iFrames


If you go the Ajax route, you can render a template server-side and return the HTML in the Ajax response:


import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def render_template(request):
result = {'html': render_to_string('your-template.html', {})}
return HttpResponse(json.dumps(result, ensure_ascii=False),
content_type='application/json')

Then you can use jQuery or whatever you want to update the HTML in the main page wherever you need.


Alternatively, you can use JavaScript to set the src of an iFrame on click to render a view without updating the entire page. It just depends on what's best for you in terms of user experience, maintenance, etc.



I have a short question and i am sure there is a simply answer. I have a template called base.html which looks simplified like this:


<html>
<head>
<title>{% block title %} Title {% endblock %}</title>
</head>
<body>
<div class="header">
{% block header %}My Header{% endblock %}
</div>

<div class="navigation">
{% block navigation %}My Navi{% endblock %}
</div>

<div class="content">
{% block content %}Content{% endblock %}
</div>
</body>
</html>

When i click on a link in the navi i want to render the new content in the content block without loading the header and die navigation again.


Thanks



You have a couple of choices: Ajax or iFrames


If you go the Ajax route, you can render a template server-side and return the HTML in the Ajax response:


import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def render_template(request):
result = {'html': render_to_string('your-template.html', {})}
return HttpResponse(json.dumps(result, ensure_ascii=False),
content_type='application/json')

Then you can use jQuery or whatever you want to update the HTML in the main page wherever you need.


Alternatively, you can use JavaScript to set the src of an iFrame on click to render a view without updating the entire page. It just depends on what's best for you in terms of user experience, maintenance, etc.


0 commentaires:

Enregistrer un commentaire