更改基于用户代理的Django模板 [英] Change Django Templates Based on User-Agent

查看:86
本文介绍了更改基于用户代理的Django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一个Django的网站,但是我已经喝了Koolaid,而且我想制作一个IPhone 的版本。经过多番思考,我提出了两个选择:

I've made a Django site, but I've drank the Koolaid and I want to make an IPhone version. After putting much thought into I've come up with two options:


  1. 制作一个整个其他网站,如i.xxxx.com。使用Django的站点框架将其绑定到同一个数据库中。

  2. 查找一些读取用户代理的中间件,并动态更改模板目录。

然而,我真的更喜欢选项#2我有一些保留,主要是因为Django文档不鼓励随时更改设置 。我发现一个代码段,可以做到我想要的。我的主要问题是使其尽可能无缝,我希望它对用户是自动和透明的。

I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation discourages changing settings on the fly. I found a snippet that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.

有其他人遇到同样的问题吗?有没有人会分享他们如何处理制作iPhone版本的Django网站?

Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?

更新

我结合了中间件和调整模板调用。

I went with a combination of middleware and tweaking the template call.

对于中间件,我使用了 minidetector 。我喜欢它,因为它检测到一个多余的移动用户代理。所有我需要做的是在我的意见中检查request.mobile。

For the middleware, I used minidetector. I like it because it detects a plethora of mobile user-agents. All I have to do is check request.mobile in my views.

对于模板调用tweak:

For the template call tweak:

 def check_mobile(request, template_name):
     if request.mobile:
         return 'mobile-%s'%template_name
     return template_name

我使用这个视图,我知道我有两个版本。

I use this for any view that I know I have both versions.

TODO:


  • 找出如何访问请求mobile 一个扩展版本的render_to_response,所以我不必使用check_mobile('template_name.html')

  • 如果没有移动版本,使用上一个自动回退到常规模板。 >
  • Figure out how to access request.mobile in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')
  • Using the previous automagically fallback to the regular template if no mobile version exists.

推荐答案

而不是动态更改模板目录,您可以修改请求并添加一个值,让您的视图知道用户是否在iphone上。然后包装render_to_response(或任何您用于创建HttpResponse对象的东西),以获取iphone版本的模板,而不是标准的html版本,如果他们使用的是iphone。

Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone.

这篇关于更改基于用户代理的Django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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