Search code examples
pythonjinja2templating-engine

Creating a table using jinja2


I am trying to create a (latex) table using jinja2. I defined a macro to help me to create the table:

{% macro table(header, rows, columns) %}
\begin{tabular}{(formatting, later)}
  {{ row(header) }}
  {% for row in rows %}
    {% for column in columns %}
    {{ caller(row, column) }} & % *here*
    {% endfor %} \\
  {% endfor %}
\end{tabular}
{% endmacro %}

I can use the template like this:

{% call(row, column) table.table(header, rows, columns) %}
  Content at row = {{row}}, column = {{column}}
{% endcall %}

I quite like how these macros work. The problem is however that I would like to join the results of the macro by a & sign rather than playing a sign after each row. Essentially now I have this:

    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 & \\

and I would like to get this instead:

    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 \\

Is it possible to use filters on macro results? Is there some other way to generate a table where each cell is another jinja2 template depending on parameters?


Solution

  • I'm not familiar with a join functionality in Jinja itself. However it does have built in indexes on your loop. Using loop.last you can determine where to change the output symbol

        {% macro table(header, rows, columns, ) %}
        \begin{tabular}{(formatting, later)}
          {{ row(header) }}
          {% for row in rows %}
            {% for column in columns %}
            {{ caller(row, column) }} {% if loop.last %}\\{% else %}&{%endif%}
            {% endfor %}
          {% endfor %}
        \end{tabular}
        {% endmacro %}
    

    Here's documentation on the other loop variables that are available: http://jinja.pocoo.org/docs/2.9/templates/#for