8

I'm trying to use a conditional in the column setup for my tabular. That is, the definition of one column (actually several columns) is dependent on a boolean value (as set up from the etoolbox package).

I need the array package too, but once I add it in (or other packages that rely on it), I get an error:

! Package array Error:  Illegal pream-token (\ifbool): `c' used.

I've tried packing my column definition into a new column type as described here, as well as some csname tricks described here, to no avail.

Here's a minimal (non-)working example

\documentclass{article}
\usepackage{etoolbox}
\usepackage{array}

\newbool{MyBoolean} \setbool{MyBoolean}{true}

\begin{document}

\begin{tabular}{
    l
    \ifbool{MyBoolean}{c}{}
    r
}

Left & \ifbool{MyBoolean}{Center &}{} Right \\
Left & \ifbool{MyBoolean}{Center &}{} Right
\end{tabular}

\end{document}

Any ideas?

  • Related/duplicate http://tex.stackexchange.com/questions/16604/easiest-way-to-delete-a-column – egreg May 26 '14 at 09:24

1 Answers1

6

I would use collcell to collect and conditionally set the column entry:

enter image description here

\documentclass{article}
\usepackage{etoolbox,array,collcell}
\newcolumntype{C}{>{\collectcell\usermacro}c<{\endcollectcell}}
\newcommand{\usermacro}[1]{\ifbool{MyBoolean}{#1}{\hspace*{-2\tabcolsep}}}

\newbool{MyBoolean}

\begin{document}

% Control tabular    
\begin{tabular}{ l c r }
  Left & Center & Right \\
  Left & Center & Right
\end{tabular}

\setbool{MyBoolean}{true}
\begin{tabular}{ l C r }
  Left & Center & Right \\
  Left & Center & Right
\end{tabular}

\setbool{MyBoolean}{false}
\begin{tabular}{ l C r }
  Left & Center & Right \\
  Left & Center & Right
\end{tabular}

\end{document}

The correction for a false boolean is to remove any column separation (of width \tabcolsep) using a negative space.

Werner
  • 603,163
  • Thanks; I think this is getting me in the right direction. Unfortunately, my real need is more complicated (in a way I didn't anticipate) than the example I put above. I need the C column to take a width parameter (like p{2cm}). Ideally I would also pass it the boolean to decide whether or not to make the column (rather than having \usermacro do that) but it's not a big deal. – Jonah Greenthal May 26 '14 at 23:39
  • @Jonah: It is possible to make C accept an argument like p{2cm}. If you're always have either the C-column or not, then it seems sufficient to have a macro construct the column (correcting the spacing if it actually doesn't exist). – Werner May 26 '14 at 23:41
  • It required some more finicking because I actually wanted to use a custom column with argument, but turned out not to be a big deal. Thanks for the help! – Jonah Greenthal May 27 '14 at 00:02