动态生成表格数据,包括`\hline`

动态生成表格数据,包括`\hline`

我的问题与这个问题但与此不同,我需要\hline在每一行之后添加一个\tabledata。我该怎么做?

目前我的代码如下:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\makeatletter
\newcommand{\myTable}[1]{%
    \def\tabledata{}% reset \tabledata
    \foreach \lhs/\rhs in {#1} {% build table data from #1  
        \protected@xappto\tabledata{\textbf{\lhs} & \rhs \\}
    }%
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \tabledata \hline
    \end{tabular}
}
\makeatother

\begin{document}
   \myTable{{Title 1}/{Description 1}, {Title 2}/{Description 2}}
\end{document}

如果我\hline简单地补充一下:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\makeatletter
\newcommand{\myTable}[1]{%
    \def\tabledata{}% reset \tabledata
    \foreach \lhs/\rhs in {#1} {% build table data from #1  
        \protected@xappto\tabledata{\textbf{\lhs} & \rhs \\ \hline}
    }%
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \tabledata \hline
    \end{tabular}
}
\makeatother

\begin{document}
   \myTable{{Title 1}/{Description 1}, {Title 2}/{Description 2}}
\end{document}

错误:

Missing control sequence inserted.

日志档案:

<inserted text> 
                \inaccessible 
l.19 ...Description 1}, {Title 2}/{Description 2}}
                                                  
Please don't say `\def cs{...}', say `\def\cs{...}'.
I've inserted an inaccessible control sequence so that your
definition will be completed without mixing me up too badly.
You can recover graciously from this error, if you're
careful; see exercise 27.2 in The TeXbook.

并且还产生以下结果: 在此处输入图片描述

答案1

\noexpand在 之前添加\hline

\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\makeatletter
\newcommand{\myTable}[1]{%
    \def\tabledata{}% reset \tabledata
    \foreach \lhs/\rhs in {#1} {% build table data from #1  
        \protected@xappto\tabledata{\textbf{\lhs} & \rhs \\\noexpand\hline}
    }%
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \tabledata %\hline %don't need
    \end{tabular}
}
\makeatother

\begin{document}
   \myTable{{Title 1}/{Description 1}, {Title 2}/{Description 2},{Title 3}/{Description 3}}
\end{document}

在此处输入图片描述

答案2

以下是不包含以下内容的 LaTeX3 版本tikz

\documentclass{article}

\ExplSyntaxOn
\cs_new:Npn \my_print_row:n #1 {
    \tl_set:Nn \l_tmpa_tl {#1}
    \regex_replace_all:nnN {(.+)/(.+)} {\c{textbf}{\1} & \2} \l_tmpa_tl
    \tl_use:N \l_tmpa_tl \\ \hline
}

\NewDocumentCommand {\myTable} { >{\SplitList{,}}m } {
    \begin{tabular}{p{0.35\textwidth}|p{0.65\textwidth}}
        \hline
        Headline 1 & Headline 2 \\ \hline
        \ProcessList{#1}{\my_print_row:n}
    \end{tabular}
}
\ExplSyntaxOff

\begin{document}
    \myTable{Title 1/Description 1,Title 2/Description 2,Title 3/Description 3}
\end{document}

在此处输入图片描述

相关内容