views:

119

answers:

2

I have a custom table-environment defined with \newenvironment. I have a caption in this environment, but I want to have it at the end.

My environment looks (a little simplified) like this:

\newenvironment{mytable}[2]{\begin{table}[hbtp]\caption{#1}\label{#1}\begin{center}\begin{tabular}{#2}}{\end{tabular}\end{center}\end{table}}

I wanna put the caption at the end, like this:

\newenvironment{mytable}[2]{\begin{table}[hbtp]\label{#1}\begin{center}\begin{tabular}{#2}}{\caption{#1}\end{tabular}\end{center}\end{table}}

But that doesn't work, because I cannot use the parameters in the end of the environment. How can I solve this problem?

A: 

use cut and paste instead of a new environment? i am fairy certain the \newenv. is not meant to be used in that manner. what is the point of this? to not type it all out every time?

Mica
To not type it out all time. To change the look of the tables over the whole book in one run. To have clearly same style on all tables. The typical reasons for DRY. You could ask what the point in defining environments or new commands is at all.
Mnementh
well, the point of defining a new environment at all is so that it would have its own counters, instead of being counted as a table or figure... but this seems fairly pointless.
Mica
+2  A: 

You'll want to store the caption and label parameters and use them later. (Also, the \label should appear after the \caption.)

Something like this should work:

\newcommand{\templabel}{}% stores the label
\newcommand{\tempcaption}{}% stores the caption

\newenvironment{mytable}[3]{%
  \gdef{\templabel}{#1}% store the label so we can use it later
  \gdef{\tempcaption}{#2}% store the caption so we can use it later
  \begin{table}[hbtp]% 
    \begin{center}%
      \begin{tabular}{#3}%
}{%
        \caption{\tempcaption}% use the stored caption
        \label{\templabel}% use the stored label (*after* the caption)
      \end{tabular}%
    \end{center}%
  \end{table}%
}

Use the environment like this:

\begin{mytable}{tab:example}{This is the caption for my example table.}{cc}
  Row 1 & First \\
  Row 2 & Second \\
  Row 3 & Third \\
\end{mytable}

I haven't tested this code.

godbyk
Thanks alot. But it turned out that \gdef didn't work. Instead I used \renewcommand and all works as I want. Thank you.
Mnementh
Ah, I messed that up. The braces around the gdef command shouldn't be there: \gdef\templabel{#1} \gdef\tempcaption{#2}Sorry. That's what I get for not testing my code first.
godbyk
Use `\centering` instead of the center environment. The latter adds in unnecessary extra vertical space.
Will Robertson
What's the protocol? Should I edit my answer to make it correct (so it's easier for others to copy/paste), or leave it as-is so that the comments make sense?
godbyk