【问题标题】:Alternative mobile templates for a mako+flask-django appmako+flask-django 应用程序的替代移动模板
【发布时间】:2016-11-03 16:13:22
【问题描述】:

我们有一个融合了flask和django的应用程序,它使用mako作为模板引擎,我们希望在用户使用移动设备时在某些视图中提供替代模板,目前我所做的是我的模板文件夹中有两个子文件夹并覆盖渲染方法以获取适当的 mako

templates
   mobile
     base.mako
     index.mako
   desktop
     base.mako
     index.mako
     results.mako

因此,例如,如果我调用 render("index.mako") 并且请求具有 request.mobile==True ,那么它会将文件 url 转换为 mobile/index.mako ,如果 'mobile/{some template}.mako' 没有'如果不存在,它将自动获取“桌面/{some template}.mako”,因为桌面存在所有模板。 现在问题来自于继承,假设我有以下模板

results.mako

<%inherit file="base.mako" />
<select>
------
</select>

我用 request.mobile==True 调用 render("results.mako") ,路径将转换为 desktop/results.mako (因为 results.mako 不存在用于移动设备)并且 results.mako 将从 'desktop/base.mako' 继承(因为它使用相对路径)而不是正确的 'mobile/base.mako' 应该使用,因为它是一个移动设备并且 mobile/base.mako 存在。

关于如何以优雅的方式解决这个问题(避免在 mako 中使用 ifs)有什么想法吗?也许通过改变 dir make 认为模板所在的位置?

【问题讨论】:

    标签: django mako


    【解决方案1】:

    我通过重写 mako 的 TemplateLookup 对象的 get_template 方法解决了这个问题。

        #override the template loading function in order to load the mobile ones when needed
        def get_template(self, uri):
            is_mobile_version=False
            has_mobile_view=False;
    
            u = re.sub(r'^\/+', '', uri).replace("mobile/","").replace("desktop/","")
            for dir in self.directories:
                dir = dir.replace(os.path.sep, posixpath.sep)
    
                mobile_file = posixpath.normpath(posixpath.join(dir, "mobile/" + u))
    
                if os.path.isfile(mobile_file):
                    has_mobile_view = True
    
                if (local.request.cookies.get("mobile") == "true"):
                    is_mobile_version = True
    
                    local.response_headers['has_mobile_view'] = has_mobile_view
                    local.response_headers["mobile"] = True
    
                    if (has_mobile_view):
                        local.response_headers['is_mobile_version'] = is_mobile_version
                        return self._load(mobile_file, "mobile/" + u)
    
                desktop_file = posixpath.normpath(posixpath.join(dir, "desktop/" + u))
                if (os.path.isfile(desktop_file)):
                    return self._load(desktop_file, uri)
                else:
                    raise exceptions.TopLevelLookupException(
                        "Cant locate(desktop or mobile) template for uri %r" % uri)
        func_type=type(TemplateLookup.get_template)
        self.template_env.get_template = func_type(get_template, self.template_env, TemplateLookup)
    

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2020-12-18
      • 2013-01-17
      • 1970-01-01
      • 2013-03-08
      • 2015-01-06
      • 1970-01-01
      • 2016-08-02
      • 2013-06-13
      相关资源
      最近更新 更多