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

查看:42
本文介绍了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/etc.应用程序环境而不是网页,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天全站免登陆