I am trying to build a table, and inside the tabularx environment I would like to have a loop, something like (here is a MWE):
\documentclass[10pt,a4paper]{article}
\usepackage{tabularx}
\usepackage{tikz}
\newcommand{\nRows}{5}
\begin{document}
\begin{tabularx}{\textwidth}{@{}>{\raggedright}p{2.2cm}@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}}
\foreach \r in {1,...,\nRows}{ % https://stackoverflow.com/questions/2561791/iteration-in-latex
\textbf{column1} & two & three & four & five
}
\end{tabularx}
\end{document}
This doesn't work, because the ampersands (&) are causing problems. If I escape the &s, then the entire line gets printed in the first column, along with the literal ampersands, kind of like:
\documentclass[10pt,a4paper]{article}
\usepackage{tabularx}
\usepackage{tikz}
\newcommand{\nRows}{5}
\begin{document}
\begin{tabularx}{\textwidth}{@{}>{\raggedright}p{2.2cm}@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}}
\foreach \r in {1,...,\nRows}{ % https://stackoverflow.com/questions/2561791/iteration-in-latex
\textbf{column1} \& two \& three \& four \& five
}
\end{tabularx}
\end{document}
This yields:
|column1 & | | | |
| two & three & | | | |
| four & five | | | |
Whereas what I want is:
|column 1 | two | three | four | five |
|column 1 | two | three | four | five |
|column 1 | two | three | four | five |
....
Any ideas on how I can achieve this? I'm actually NOT looking to make identical rows - the rows will be different. This is just a MWE. Thanks!
Edit: I have tried implementing Herbert's answer as recommended in the comments section. It results in no output - just a blank PDF. Here is how I implemented it:
\documentclass[10pt,a4paper]{article}
\usepackage{tabularx}
\usepackage{tikz}
\newcommand{\nRows}{5}
\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand*\resettabtoks{\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}
\makeatother
\begin{document}
\resettabtoks
\foreach \r in {1,...,\nRows}{ % https://stackoverflow.com/questions/2561791/iteration-in-latex
% \textbf{column1} \& two \& three \& four \& five
\addtabtoks{\textbf{column1} & two & three & four & five \\\hline}%
}
\begin{tabularx}{\textwidth}{@{}>{\raggedright}p{2.2cm}@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}>{\raggedright}X@{}}
\printtabtoks
\end{tabularx}
\end{document}
Any ideas on what I am doing wrong? Thanks!
\documentclass{...}
and ending with\end{document}
.\raggedright\arraybackslash
in your preamble.\global\@tabtoks
, because\foreach
executes each cycle in a group. Related: tex.stackexchange.com/questions/62177/copy-table-row-n-times\arraybackslash
after\raggedright
in the last column specification.