【问题标题】:Access jinja2 templates from a folder outside of package从包外的文件夹访问 jinja2 模板
【发布时间】:2021-11-02 11:16:53
【问题描述】:

我正在尝试使用 Wea​​syprint 和 Jinja2 生成 pdf 格式的账单 我有以下文件架构:

项目
|脚本
|| pdf_builder.py
|模板
|| bill_template.html
|| bill_style.css

但是无论我尝试什么,我都会收到以下错误:
jinja2.exceptions.TemplateNotFound: ../templates/bill_template.html

我对 pdf_builder.py 的相关代码是:

from weasyprint import HTML
from jinja2 import Environment, FileSystemLoader

file_html = "../templates/bill_template.html"

# loading the jinja2 environment
env = Environment(loader=FileSystemLoader('../templates'))

# Render and build
template = env.get_template(file_html)
html_out = template.render()
HTML(string=html_out).write_pdf(pdf_name, stylesheets=[file_css])

真的不可能使用 jinja 从当前文件夹之外的文件夹访问模板吗?还是我把路径都弄错了?提前感谢您的帮助!

【问题讨论】:

    标签: python templates package jinja2 weasyprint


    【解决方案1】:

    找到了……

    对于 jinja,您需要在 FileSystemLoader 中指定模板文件夹所在的位置,然后从中给出模板文件的相对路径。

    但是对于 css(你给 Weasyprint,你必须指定工作目录的相对路径。这给出了:

    file_html = f"{document_type}_template.html"
    file_css = f"templates/{document_type}_style.css"
    
    env = Environment(loader=FileSystemLoader('templates'))
    template = env.get_template(file_html)
    html_out = template.render(template_vars)
    HTML(string=html_out).write_pdf(pdf_name, stylesheets=[file_css])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      相关资源
      最近更新 更多