3

I am trying to get into report automation with LaTeX and Jinja2 with a python script. I managed to fill a simple table with some data in a .txt file.

I would like to use variables names inside my data file containing the character "/". However python interprets the /. I tried to use filters taken from a few websites but I cannot manage to escape it.

My key is the following : <RF/Freq>. I am asking Jinja to spot terms between '<' and '>', and I have the same in the LaTeX template.

This is what my filter is at the moment :

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

But Jinja returns : jinja2.exceptions.UndefinedError: 'RF' is undefined

For info, my latex template contains :

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

Frequency & <RF\Freq | escape_tex>

\end{tabular}
\end{document}

I tried multiple solutions found on SE or other websites, but without success.

user43799
  • 31
  • 3

2 Answers2

1

As far as I understand it, you cannot. You have to replace the characters Python doesn't like in the identifiers before trying to use them in Jinja templates.

andrewsh
  • 1,115
  • 7
  • 12
1
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