Change Django Templates Based on User-Agent

前端 未结 10 2544
耶瑟儿~
耶瑟儿~ 2020-12-07 11:37

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:

10条回答
  •  醉酒成梦
    2020-12-07 11:55

    A simple solution is to create a wrapper around django.shortcuts.render. I put mine in a utils library in the root of my application. The wrapper works by automatically rendering templates in either a "mobile" or "desktop" folder.

    In utils.shortcuts:

    from django.shortcuts import render
    from user_agents import parse
    
    def my_render(request, *args, **kwargs):
      """
      An extension of django.shortcuts.render.
    
      Appends 'mobile/' or 'desktop/' to a given template location
      to render the appropriate template for mobile or desktop
    
      depends on user_agents python library
      https://github.com/selwin/python-user-agents
    
      """
      template_location = args[0]
      args_list = list(args)
    
      ua_string = request.META['HTTP_USER_AGENT']
      user_agent = parse(ua_string)
    
      if user_agent.is_mobile:
          args_list[0] = 'mobile/' + template_location
          args = tuple(args_list)
          return render(request, *args, **kwargs)
      else:
          args_list[0] = 'desktop/' + template_location
          args = tuple(args_list)
          return render(request, *args, **kwargs)
    

    In view:

    from utils.shortcuts import my_render
    
    def home(request):    return my_render(request, 'home.html')
    

提交回复
热议问题