2017-03-13 45 views
0

我想用jinja2和python來生成一個latex文檔。我使用的Jinja2和Python稱爲jinja_engine.py文件:jinja2:使用全局變量來選擇文本的乳膠塊

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} 
\setlength\parindent{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的新手。

template.render(dict_map) 

template.render(dict_map = dict_map) 

這樣我可以在template.tex文件中使用dict_map全局變量:

回答

0

嘗試了幾件事情後,我可以只由jinja_engine.py文件替換,使這項工作