2010-02-01 27 views

Trả lời

34

Tôi không tin như vậy. Thông thường, bạn bao gồm hoặc mở rộng các mẫu khác bằng cách chỉ định đường dẫn của chúng liên quan đến gốc của trình tải mẫu bất kỳ và môi trường bạn đang sử dụng.

Vì vậy, giả sử các mẫu của bạn là tất cả trong /path/to/templates và bạn đã thiết lập Jinja như vậy:

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

Bây giờ, nếu bạn muốn đưa vào /path/to/templates/includes/sidebar.html trong /path/to/templates/index.html mẫu, bạn muốn viết theo sau trong số index.html:

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

và Jinja sẽ tìm ra cách tìm.

6

Theo tài liệu cho jinja2.Environment.join_path(), hỗ trợ cho các đường dẫn mẫu tương đối có thể bằng cách ghi đè tham gia join_path() để triển khai "nối đường dẫn mẫu".

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

Chỉ cần để thêm vào câu trả lời Will McCutchen của,

Bạn có thể có nhiều thư mục trong bộ nạp của bạn. Sau đó nó tìm kiếm trong mỗi thư mục (theo thứ tự) cho đến khi nó tìm thấy mẫu.

ví dụ, nếu bạn muốn có "sidebar.html" thay vì "/includes/sidebar.html" sau đó có:

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

thay vì

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

Cách sạch để vượt qua giới hạn này, sẽ có phần mở rộng jinja2 sẽ cho phép import relative template names

Điều gì đó thích:

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 
Các vấn đề liên quan