6

I'm trying to use the tikz package's foreach command in a tabular environment. I know that it is not really suited for doing this, but how would I be able to make the following command work (I think, it is obvious what it should do, and I know that there are some difficulties regarding the textbf command as well):

\newcommand{\myTable}[1]{
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\
        \foreach \lhs/\rhs in {#1} {
            \textbf{\lhs} & \rhs \\
        }
        \hline
    \end{tabular}
}

MWE:

\documentclass{article}
\usepackage{tikz}

\newcommand{\myTable}[1]{
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\
        \foreach \lhs/\rhs in {#1} {
            \textbf{\lhs} & \rhs \\
        }
        \hline
    \end{tabular}
}

\begin{document}
\myTable{{Title 1}/{Description 1}, {Title 2}/{Description 2}}
\end{document}
8

The following slightly painful code does this using \foreach from tikz:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\makeatletter
\newcommand{\myTable}[1]{%
    \def\tabledata{}% reset \tabledata
    \foreach \lhs/\rhs in {#1} {% build table data from #1  
        \protected@xappto\tabledata{\textbf{\lhs} & \rhs \\}
    }%
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \tabledata \hline
    \end{tabular}
}
\makeatother

\begin{document}
   \myTable{{Title 1}/{Description 1}, {Title 2}/{Description 2}}
\end{document}

The trick is that you need to construct the table data first and then put it inside the tabular environment. Expanding \\ causes issues as well.

A more straightforward approach is to use \docsvlist from etoolbox:

\documentclass{article}
\usepackage{etoolbox}
\def\addtablerow#1/#2!{\textbf{#1} & #2\\}
\newcommand{\myTable}[1]{
    \renewcommand*\do[1]{\addtablerow##1!}
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \docsvlist{#1} \hline
    \end{tabular}
}

\begin{document}
    \myTable{Title 1/Description 1, Title 2/Description 2}
\end{document}

The \docsvlist command applies the (current version of) \do to each element in the comma separated list. In turn, \do calls \addtablerow, which expects two arguments, which are delimited by / and !.

In both cases you end up with:

enter image description here

Btw, in both cases you can drop many of the braces - as shown in the second example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.