开发者

Django : writing a template tag that removes content outside of it

开发者 https://www.devze.com 2023-04-06 15:07 出处:网络
I am writing a site, and some pages are requested both with Ajax, or with a normal request. Of course, when requesting with Ajax, I\'d like to render a slightly different template. I\'ve tried several

I am writing a site, and some pages are requested both with Ajax, or with a normal request. Of course, when requesting with Ajax, I'd like to render a slightly different template. I've tried several methods (A render_block snippet w开发者_StackOverflowhich was a great idea but buggy, using {% include %} to separate the templates while factorizing the code, using {% ifnot request.is_ajax %} to render content, like toolbar or menu, only if not Ajax). So I thought that it would be really cool to do like so :

<div> A menu that should not appear with Ajax </div>
{% ajax %}
<div> The Ajax part </div>
{% endajax %}
<div> A footer that should not appear with Ajax </div>

Then normal request returns :

<div> A menu that should not appear with Ajax </div>
<div> The Ajax part </div>
<div> A footer that should not appear with Ajax </div>

Ajax request :

<div> The Ajax part </div>

However, I don't really now where to start ... I've already written template tags, but never had to do something so complicated ! IS it even possible ?


That sounds like a really confusing way of doing it - I'd definitely stick to:

{% if not request.is_ajax %}
<div> A menu that should not appear with Ajax </div>
{% endif %}
<div> The Ajax part </div>
{% if not request.is_ajax %}
<div> A footer that should not appear with Ajax </div>
{% endif %}

Alternatively, separate out your templates, so that the stuff you want rendered both times is in one template (we'll call this my_ajax_template.html):

<div> The Ajax part </div>

When responding to requests that come from AJAX your view code can just render that template, but when responding to "normal" requests, you could render a template that looked like this:

<div> A menu that should not appear with Ajax </div>
{% include 'my_ajax_template.html' %}
<div> A footer that should not appear with Ajax </div>
0

精彩评论

暂无评论...
验证码 换一张
取 消