在jinja2模板中导入python库

问题描述 投票:0回答:1

我有这个模板:

% template.tmpl file:
% set result = fractions.Fraction(a*d + b*c, b*d) %}
The solution of ${{a}}/{{b}} + {{c}}/{{d}}$ is ${{a * d + b*c}}/{{b*d}} = {{result.numerator}}/{{result.denominator}}$ 

我通过

调用
from jinja2 import Template
import fractions

with open("c.jinja") as f:
    t = Template(f.read())
    a = 2
    b = 3
    c = 4
    d = 5
    print(t.render(a = a, b = b, c=c, d=d))

我明白了

jinja2.exceptions.UndefinedError: 'fractions' is undefined

但是我想要

The solution of $2/3 + 4/5$ is $22/15=22/15$.

这可以实现吗?

python jinja2
1个回答
0
投票

可以通过两种方式完成。

  1. 在Python中计算
    result
    ,然后将其作为参数传递。
  2. 您可以将
    fractions
    模块作为参数传递给模板。

文件夹结构:

.
├── c.jinja
└── template_example.py

选项 1:将

result
传递给模板:

template_example.py

from jinja2 import Template
import fractions

with open("c.jinja") as f:
    t = Template(f.read())
    a = 2
    b = 3
    c = 4
    d = 5
    result = fractions.Fraction(a * d + b * c, b * d)
    print(t.render(a=a, b=b, c=c, d=d, result=result))

c.jinja

The solution of ${{a}}/{{b}} + {{c}}/{{d}}$ is ${{a * d + b*c}}/{{b*d}} = {{result.numerator}}/{{result.denominator}}$

选项 2:通过

fractions
:

template_example.py

from jinja2 import Template
import fractions

with open("c.jinja") as f:
    t = Template(f.read())
    a = 2
    b = 3
    c = 4
    d = 5
    print(t.render(a=a, b=b, c=c, d=d, fractions=fractions))

c.jinja

{% set result = fractions.Fraction(a*d + b*c, b*d) %}
The solution of ${{a}}/{{b}} + {{c}}/{{d}}$ is ${{a * d + b*c}}/{{b*d}} = {{result.numerator}}/{{result.denominator}}$

两个选项的输出:

The solution of $2/3 + 4/5$ is $22/15 = 22/15$
© www.soinside.com 2019 - 2024. All rights reserved.