逃避Jinja2和LaTeX的斜线

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

我正在尝试使用python脚本进入LaTeX和Jinja2的报表自动化。我设法用.txt文件中的一些数据填充一个简单的表。

我想在包含字符“/”的数据文件中使用变量名。但是python解释了/。我尝试使用从几个网站获取的过滤器,但我无法逃脱它。

我的关键是以下:<RF/Freq>。我要求Jinja发现''之间的术语,我在LaTeX模板中也有相同的内容。

这就是我的过滤器目前的情况:

LATEX_SUBS = (
    (re.compile(r'\\'), r'\\textbackslash'),
    (re.compile(r'([{}_#%&$])'), r'\\\1'),
    (re.compile(r'~'), r'\~{}'),
    (re.compile(r'\^'), r'\^{}'),
    (re.compile(r'"'), r"''"),
    (re.compile(r'\.\.\.+'), r'\\ldots'),
    (re.compile(r'/'), r'\/')
)

def escape_tex(value):
    newval = value
    for pattern, replacement in LATEX_SUBS:
        newval = pattern.sub(replacement, newval)
    return newval

但Jinja回归:jinja2.exceptions.UndefinedError: 'RF' is undefined

有关信息,我的乳胶模板包含:

\documentclass[12pt,a4paper]{article} 
\begin{document}
\begin{tabular}{c|c}
Test & Result \\
\hline

Frequency & <RF\Freq | escape_tex>

\end{tabular}
\end{document}

我尝试在SE或其他网站上找到多种解决方案,但没有成功。

python automation latex jinja2
2个回答
0
投票

据我了解,你不能。在尝试在Jinja模板中使用Python之前,您必须替换标识符中不喜欢的字符。


0
投票
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(TeX_template),
)

# TeX_template is path to template

jinja_env.filters['escape_tex'] = escape_tex
© www.soinside.com 2019 - 2024. All rights reserved.