我是一名新手,正在探索模板引擎Jinja2,帮助我使用Python排版几个LaTeX文档。在我的初步探索中,我只是尝试使用以下Python代码填充表格:
latex_jinja_env = jinja2.Environment(
block_start_string = '\BLOCK{',
block_end_string = '}',
variable_start_string = '\VAR{',
variable_end_string = '}',
comment_start_string = '\#{',
comment_end_string = '}',
line_statement_prefix = '%%',
line_comment_prefix = '%#',
trim_blocks = True,
autoescape = False,
loader = jinja2.FileSystemLoader(os.path.abspath('.'))
)
header = ['Num', 'Date', 'Ticker']
data = [[1, 2, 3], [4, 'STR', 'Test'], [5, 6, 'Ticker']]
template = latex_jinja_env.get_template('template.tex')
print(template.render(section1='Test Table', header = header, data = data))
LaTeX模板的构建如下所示:
\documentclass[12pt,a4paper]{article}
\begin{document}
\section{\VAR{section1}}
\BLOCK{set colsep = joiner("&")}
\begin{tabular}{ ccc }
\hline
\BLOCK{for col in header} \VAR{colsep()} \textbf{\VAR{col}} \BLOCK{endfor} \\
\hline
\hline
\BLOCK{for row in data} \BLOCK{for col in row} \VAR{colsep()} \VAR{col} \BLOCK{endfor} \\
\BLOCK{endfor}
\hline
\end{tabular}
\end{document}
虽然标题已按要求生成,但是在数据方面出现了一个空列被插入到数据之前:
bash-3.2$ ./rep.py
\documentclass[12pt,a4paper]{article}
\begin{document}
\section{Test Table}
\begin{tabular}{ ccc }
\hline
\textbf{Num} & \textbf{Date} & \textbf{Ticker} \\
\hline
\hline
& 1 & 2 & 3 \\
& 4 & STR & Test \\
& 5 & 6 & Ticker \\
\hline
\end{tabular}
\end{document}
bash-3.2$
什么是用合适的方式向模板表格填充数据?非常感谢您帮助这位新手。