2016-07-01 21 views
0

我們有一個應用程序,這是一個燒瓶和Django的融合,它使用mako作爲模板引擎,我們希望在某些視圖中爲用戶提供替代模板移動,目前我所做的就是讓兩個子文件夾在我的模板文件夾,並在此改變渲染方法來獲取相應的灰鯖鯊mako + flask-django app的替代移動模板

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

因此,例如,如果我叫渲染(「index.mako」)和請求有request.mobile==True那麼它會將文件url轉換爲mobile/index.mako,如果'mobile/{some template} .mako'不存在,它會自動獲取'desktop/{some template} .mako',因爲所有模板都存在for桌面。現在 的問題帶有繼承,說我有下面的模板

results.mako

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

和我所說的渲染(「results.mako」)與request.mobile ==真,路徑將轉換爲desktop/results.mako(因爲results.mako不適用於移動設備)並且results.mako將從「desktop/base.mako」繼承(因爲它使用相對路徑),而不是正確的「mobile/base.mako'應該使用,因爲它的移動和移動/ base.mako存在。

任何想法如何解決這個在一個優雅的(避免if內mako)的方式?也許通過改變dir make認爲模板的位置?

回答

0

我通過重寫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)