Search code examples

Python Jinja2 LaTeX Table

I am a newbie, exploring the template engine Jinja2 to help me to typeset a couple of LaTeX documents using Python. In my initial explorations, I am simply trying to populate a table using the following code in 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))

The LaTeX-template is constructed as follows:



\BLOCK{set colsep = joiner("&")}
\begin{tabular}{ ccc }
    \BLOCK{for col in header} \VAR{colsep()} \textbf{\VAR{col}} \BLOCK{endfor}  \\         
    \BLOCK{for row in data} \BLOCK{for col in row} \VAR{colsep()}  \VAR{col}  \BLOCK{endfor} \\ 

Whilst the header is generated as wanted, concerning the data an empty column appears to be prepended to the data:

bash-3.2$ ./

\section{Test Table}

\begin{tabular}{ ccc }
      \textbf{Num}   & \textbf{Date}   & \textbf{Ticker}    \\         
    & 1   & 2   & 3    \\ 
    & 4   & STR   & Test    \\ 
    & 5   & 6   & Ticker    \\ 


What is the appropriate manner fill the template table with data? Thanks in advance for helping out this newbie.


  • I don't know if you find answer but try like this:

    data2 = [[1, 2, 3], [4, 'STR', 'Test'], [5, 6, 'Ticker']]
    renderer_template = template.render(dict_map = data2, header = header)

    You should paste your data like dictionary and because of that you can each element of data separately.

    Then in you template.tex file you will have something like this:

    \begin{tabular}{ ccc  }
         \BLOCK{for col in header} 
        \BLOCK{if loop.last} %checks if loop reached to the end
            \VAR{col} &
        \BLOCK{endfor}  \\  
        \BLOCK{for col in dict_map} 
        \VAR{col[0]} & \VAR{col[1]} & \VAR{col[2]}  \\
        \BLOCK{endfor}  \\  

    In your code header was printing only in one column, and if you want to each item in header be in seperate column than you must get item of header as item1 & item2 but the last item doesn't have a sign "&" so you must check when the loop reach to last item that is "loop.last". Same thing for data you must get each subitem of item in data for example col[0] gets 1 and so on.

    p.s. I am not expert in latex and jinja2