Change Django Templates Based on User-Agent

前端 未结 10 2520
耶瑟儿~
耶瑟儿~ 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:58

    This article might be useful: Build a Mobile and Desktop-Friendly Application in Django in 15 Minutes

    0 讨论(0)
  • 2020-12-07 12:01

    best possible scenario: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so

    from django.shortcuts import render_to_response
    from django.template import RequestContext
    
    def my_view_on_mobile_and_desktop(request)
        .....
        render_to_response('regular_template.html', 
                           {'my vars to template':vars}, 
                           context_instance=RequestContext(request))
    

    then in your template you are able to introduce stuff like:

    <html>
      <head>
      {% block head %}
        <title>blah</title>
      {% if request.mobile %}
        <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
      {% else %}
        <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
      {% endif %}
      </head>
      <body>
        <div id="navigation">
          {% include "_navigation.html" %}
        </div>
        {% if not request.mobile %}
        <div id="sidebar">
          <p> sidebar content not fit for mobile </p>
        </div>
        {% endif %>
        <div id="content">
          <article>
            {% if not request.mobile %}
            <aside>
              <p> aside content </p>
            </aside>
            {% endif %}
            <p> article content </p>
          </aricle>
        </div>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-07 12:02

    Other way would be creating your own template loader that loads templates specific to user agent. This is pretty generic technique and can be use to dynamically determine what template has to be loaded depending on other factors too, like requested language (good companion to existing Django i18n machinery).

    Django Book has a section on this subject.

    0 讨论(0)
  • 2020-12-07 12:03

    You should take a look at the django-mobileadmin source code, which solved exactly this problem.

    0 讨论(0)
提交回复
热议问题