2010-02-01 86 views

回答

34

我不這麼認爲。通常,您可以通過指定相對於您所使用的任何模板加載器和環境的根的路徑來包含或擴展其他模板。

所以我們說你的模板都在/path/to/templates,你已經設置了神社就像這樣:

import jinja2 
template_dir = '/path/to/templates' 
loader = jinja2.FileSystemLoader(template_dir) 
environment = jinja2.Environment(loader=loader) 

現在,如果你想包括/path/to/templates/includes/sidebar.html/path/to/templates/index.html模板,你會寫在你的index.html

{% include 'includes/sidebar.html' %} 

和Jinja會弄清楚如何找到它。

6

根據jinja2.Environment.join_path()的文檔,可以通過重寫join_path()來實現「模板路徑連接」來支持相對模板路徑。

class RelEnvironment(jinja2.Environment): 
    """Override join_path() to enable relative template paths.""" 
    def join_path(self, template, parent): 
     return os.path.join(os.path.dirname(parent), template) 
14

我想補充威爾MCCUTCHEN的回答,

你可以在你的裝載機多個目錄。然後它會搜索每個目錄(按順序)直到找到模板。

例如,如果你想擁有 「sidebar.html」 而不是 「/includes/sidebar.html」 則有:

loader=jinja2.FileSystemLoader(
     [os.path.join(os.path.dirname(__file__),"templates/includes"), 
     os.path.join(os.path.dirname(__file__),"templates")]) 

,而不是

loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),"templates")) 
2

最乾淨的方式克服這個限制,將與jinja2擴展,將允許import relative template names

東西喜歡:

from jinja2.ext import Extension 
import re 


class RelativeInclude(Extension): 
    """Allows to import relative template names""" 
    tags = set(['include2']) 

    def __init__(self, environment): 
     super(RelativeInclude, self).__init__(environment) 
     self.matcher = re.compile("\.*") 

    def parse(self, parser): 
     node = parser.parse_include() 
     template = node.template.as_const() 
     if template.startswith("."): 
      # determine the number of go ups 
      up = len(self.matcher.match(template).group()) 
      # split the current template name into path elements 
      # take elements minus the number of go ups 
      seq = parser.name.split("/")[:-up] 
      # extend elements with the relative path elements 
      seq.extend(template.split("/")[1:]) 
      template = "/".join(seq) 
      node.template.value = template 
     return node 
相關問題