Jinja2:使用全局变量选择文本的乳胶块



我正在尝试使用jinja2和python生成乳胶文档。我有一个使用jinja2和python的文件,称为 jinja_engine.py

import jinja2
import os

dict_map = {
    'case1' : [1,2,3],
    'case2' : [1,3],
    'case3' : [3]
}
latex_jinja_env = jinja2.Environment(
block_start_string = '((*',
block_end_string = '*))',
variable_start_string = '(((',
variable_end_string = ')))',
comment_start_string = '((=',
comment_end_string = '=))',
loader = jinja2.FileSystemLoader(os.path.abspath('.'))
)
template = latex_jinja_env.get_template('template.tex')
template.render(dict_map)

我想使用 dict_map字典(全局变量)选择应在乳胶中渲染的文本块,哪些应该不是。template.tex看起来像这样:

documentclass[12pt]{article}
usepackage{geometry}
geometry{letterpaper,tmargin=1in,bmargin=1in,lmargin=1.4in,rmargin=1.4in}
setlengthparindent{0pt}
usepackage{xcolor,soul}
sethlcolor{yellow}
sloppy
begin{document}

((* for i in dict_map['case3'] *))
  ((* if i == 1 *))
  This is the first block  \[10pt]
  ((* elif i == 2 *))
  This is the second block \[10pt]
  ((* else *))
  This is the third block \[10pt]
  ((* endif *))
((* endfor* ))
end{document}

在这种情况下,仅应渲染This is the third block字符串。我正在尝试运行python jinja_engine.py,但我的dict_map未定义。如何将dict_map传递给jinja.Environment并在我的template.tex中使用它?我是Jinja2的新手。

尝试了几件事,我只需在jinja_engine.py文件中替换即可完成此工作:

template.render(dict_map)

template.render(dict_map = dict_map)

通过这种方式,我可以在template.tex文件中使用dict_map全局变量

最新更新