如何使用LaTeX创建一个带有标题的自定义表环境?

Mne*_*nth 5 latex tex newenvironment latex-environment

我有一个使用\newenvironment定义的自定义表环境.我在这个环境中有一个标题,但我想最后拥有它.

我的环境看起来(有点简化)像这样:

\newenvironment{mytable}[2]{\begin{table}[hbtp]\caption{#1}\label{#1}\begin{center}\begin{tabular}{#2}}{\end{tabular}\end{center}\end{table}}
Run Code Online (Sandbox Code Playgroud)

我想把标题放在最后,像这样:

\newenvironment{mytable}[2]{\begin{table}[hbtp]\label{#1}\begin{center}\begin{tabular}{#2}}{\caption{#1}\end{tabular}\end{center}\end{table}}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为我无法在环境结束时使用这些参数.我怎么解决这个问题?

god*_*byk 4

您需要存储标题和标签参数并在以后使用它们。(此外,\label 应出现在 \caption 之后。)

像这样的东西应该有效:

\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}%
}
Run Code Online (Sandbox Code Playgroud)

使用环境如下:

\begin{mytable}{tab:example}{This is the caption for my example table.}{cc}
  Row 1 & First \\
  Row 2 & Second \\
  Row 3 & Third \\
\end{mytable}
Run Code Online (Sandbox Code Playgroud)

我还没有测试过这段代码。