2016-07-01 8 views
0

우리는 flasks와 django의 융합이며 mako를 템플릿 엔진으로 사용하는 app를 가지고 있습니다. 사용자가 켜져있을 때를위한 몇 가지보기에서 대안 템플릿을 제공하고자합니다 모바일, 현재 내가 무슨 짓을하는 것은 내 템플릿 폴더에 두 개의 하위 폴더를 만들고 적절한 마코를 잡기 위해 render 메소드를 오버라이드 (override)하는 것입니다mako + flask-django 앱을위한 대체 모바일 템플릿

그래서
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'를 가져옵니다. 바탕 화면. 문제는 이제 상속되어, 나는 다음과 같은 템플릿

results.mako

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

가 있다고 나는, 경로 == request.mobile로 ("results.mako")를 렌더링 진정한 전화 results.mako는 모바일 용으로 존재하지 않으므로 desktop/results.mako로 변환하고 results.mako는 'desktop/base.mako'에서 상속받습니다 (관련 경로를 사용하므로). 올바른 '모바일/base.mako '는 모바일 이후에 사용해야하며 mobile/base.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)