[Tex/LaTex] How to separate table content and table style

formattingtables

I want to know if there is a way to separate table / content for table style (think CSS).

Like to have only data specification

\begin{tabular}
H1 & H2 & H3 & h4 \\
V1 & V2 & V3 & V4 \\
\end{tabular}

And then have the style somewhere to have the heading bold, the line filled, etc.

Best Answer

You can separate content and format in (La)TeX by defining your own logical format macros which are then (re)defined to the physical format macros required for each particular table.

For example the following table is used coded once but can be used with different styles. Normally the table might be in a user document or in a .tex file on its own and the styles could be placed in .sty files.

\documentclass{article}

\usepackage{array}
\usepackage{booktabs}

\newcommand\DEMOTABLE{%
\begin{tabular}{1234} \beforeheading
\heading{H1}&\heading{H2}&\heading{H3}&\heading{h4}\\\afterheading
V1 & V2 & V3 & V4 \\\normalline
V1 & V2 & V3 & V4 \\\normalline
V1 & V2 & V3 & V4 \\\lastline
\end{tabular}
}

\begin{document}

% Default
\newcolumntype{1}{l}
\newcolumntype{2}{l}
\newcolumntype{3}{l}
\newcolumntype{4}{l}
\newcommand*\heading{}
\newcommand*\beforeheading{}
\newcommand*\afterheading{}
\newcommand*\normalline{}
\newcommand*\lastline{}

\par\bigskip\noindent
Default:\\[\smallskipamount]
\DEMOTABLE

% All rules
\newcolumntype{1}{|l}
\newcolumntype{2}{|l}
\newcolumntype{3}{|l}
\newcolumntype{4}{|l|}
\renewcommand*\heading{\bfseries}
\renewcommand*\beforeheading{\hline}
\renewcommand*\afterheading{\hline}
\renewcommand*\normalline{\hline}
\renewcommand*\lastline{\hline}

\par\bigskip\noindent
Rules:\\[\smallskipamount]
\DEMOTABLE

% Nice looking rules, centered cells
\newcolumntype{1}{c}
\newcolumntype{2}{c}
\newcolumntype{3}{c}
\newcolumntype{4}{c}
\renewcommand*\heading[1]{\bfseries\MakeUppercase{#1}}
\renewcommand*\beforeheading{\toprule}
\renewcommand*\afterheading{\midrule}
\renewcommand*\normalline{}
\renewcommand*\lastline{\bottomrule}

\par\bigskip\noindent
Nice:\\[\smallskipamount]
\DEMOTABLE

\end{document}

Result:

enter image description here

Related Question