[Tex/LaTex] Using conditionals in tabular preamble with array

conditionalsetoolboxtables

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?

Best Answer

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.