代码之家  ›  专栏  ›  技术社区  ›  joeforker

Jinja2模板语言是否有“here”(当前目录)的概念?

  •  22
  • joeforker  · 技术社区  · 15 年前

    Jinja2是否支持模板相对路径,例如。 %(here)s/other/template.html ,以包含与当前模板在文件系统中的位置相关的其他模板?

    4 回复  |  直到 15 年前
        1
  •  41
  •   Will McCutchen    15 年前

    我不这样认为。通常,您可以通过指定其他模板相对于所使用的任何模板加载程序和环境的根的路径来包括或扩展其他模板。

    假设你的模板都是这样的 /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' %}
    

        2
  •  18
  •   Rusty Rob    13 年前

    再加上威尔·麦库钦的回答,

    加载程序中可以有多个目录。然后在每个目录中搜索(按顺序),直到找到模板。

    例如,如果您希望使用“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"))
    
        3
  •  9
  •   t-mart Mike Lewis    5 年前

    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)
    
        4
  •  2
  •   Janusz Skonieczny    11 年前

    克服这一限制的最干净的方法是使用允许 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