Django 部分模板响应 [英] Django partial template responses

查看:30
本文介绍了Django 部分模板响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它被认为是正确的/将部分模板返回给ajax POST请求是否有任何陷阱?

Is it considered correct/ are there any pitfalls in returning partial templates to ajax POST requests?

例如:

if request.is_ajax:
    # response is just the form 
    return render(request, 'contact/fields.html', {'form':form})

推荐答案

最典型的方法是返回 JSON,然后从 JSON 数据构建客户端所需的任何 HTML.然而,可以说这是混合了表现和行为,最好将 HTML 清楚地分开.

The most typical approach is returning JSON and then contructing whatever HTML you need client-side from the JSON data. However, it could be argued that this is mixing presentation with behavior and it would be better to clearly separate out the HTML.

另一方面,返回一个 HTML 块大约是RESTful"的极南.在纯 REST 哲学中,视图应该在标准且可重用的容器(例如 JSON 或 XML)中返回数据.稍后如果您需要将表单拉入 iOS/Android/WP7/等.应用程序环境而不是网页,JSON/XML 也可以为您服务,而 HTML 几乎没有用.

On the flip-side, returning a block of HTML is about as polar-south of "RESTful" as you can get. In pure REST philosophy, the views should return data in a standard and reusable container (such as JSON or XML). Later if you needed to pull the form into an iOS/Android/WP7/etc. app environment rather than a webpage, the JSON/XML will serve you just as well, whereas the HTML is virtually useless.

我可以很容易地看到这两种论点,而且我认为其中一个不一定比另一个更正确.最终,我认为您只需要做最适合您的应用程序以及您感觉正确"的事情.根据您的特定情况考虑什么更易于维护和扩展.

I can easily see both arguments, and I don't think one is necessarily more right than the other. Ultimately, I think you just have to do what works best for your app and what "feels right" to you. Think in terms of what is more maintainable and extensible for your particular circumstances.

这篇关于Django 部分模板响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆