基于 User-Agent 更改 Django 模板 [英] Change Django Templates Based on User-Agent

查看:33
本文介绍了基于 User-Agent 更改 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 文档不鼓励动态更改设置.我找到了一个 snippet 可以满足我的需求.我的主要问题是让它尽可能无缝,我希望它是自动的,对用户透明.

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.

对于模板调用调整:

 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.

待办事项:

  • 弄清楚如何在 render_to_response 的扩展版本中访问 request.mobile,这样我就不必使用 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.

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

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