我有这个模板:
% 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$.
这可以实现吗?
可以通过两种方式完成。
result
,然后将其作为参数传递。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$