我试图在表格中扩展多个宏以自动添加不同的背景颜色,但没有考虑到颜色:
\documentclass{memoir}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{booktabs}
\NewExpandableDocumentCommand{\yes}{O{Yes}m}{\SetCell{bg=green9} #1}
\NewExpandableDocumentCommand{\no}{O{No}m}{\SetCell{bg=red8} #1}
\begin{document}
\begin{tblr}[expand=\expandafter]{cc}
What I want & is below\\
\SetCell{bg=green9} Yes & \SetCell{bg=red8} No\\
\SetCell{bg=green9} Great & \SetCell{bg=red8} Bad\\
What I get & is below\\
\expandafter\empty\yes{} & \expandafter\empty\no{}\\
\expandafter\empty\yes[Great]{} & \expandafter\empty\no[Bad]{}
\end{tblr}
\end{document}
相关,但不能解决我的问题:tabulararray:不能使用 def 来设置单元格属性? tabularray:展开多个宏
答案1
摘自手册tabularray
:
因此,没有可选参数。这是不可能的。而且只有一宏可以扩展。
\documentclass{memoir}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{booktabs}
\newcommand{\yn}[2]{\SetCell{bg=\if#1ygreen9\else red8\fi}#2}
\begin{document}
\begin{tblr}[expand=\yn]{cc}
What I want & is below\\
\SetCell{bg=green9} Yes & \SetCell{bg=red8} No\\
\SetCell{bg=green9} Great & \SetCell{bg=red8} Bad\\
What I get & is below\\
\yn{y}{Yes} & \yn{n}{No}\\
\yn{y}{Great} & \yn{n}{Bad}
\end{tblr}
\end{document}
可能更好的定义\yn
是
\ExplSyntaxOn
\cs_new:Npn \yn #1 #2
{
\SetCell{bg=\str_case:nn {#1}{{y}{green9}{n}{red8}}}#2
}
\ExplSyntaxOff
使用标准方法:
\documentclass{memoir}
\usepackage[table]{xcolor}
\usepackage{ninecolors}
\NewExpandableDocumentCommand{\yes}{O{Yes}m}{\cellcolor{green9}#1}
\NewExpandableDocumentCommand{\no}{O{No}m}{\cellcolor{red8}#1}
\begin{document}
\begin{tabular}{cc}
First & Second \\
\yes{} & \no{}\\
\yes[Great]{} & \no[Bad]{}
\end{tabular}
\end{document}
答案2
如果您不需要命令中的任何文本,而只是想要一个更短的宏名\SetCell{bg=red8}
,那么tabularray
可以使用以下命令\NewTableCommand
(请参阅文档的第 3.6 节和第 3.2.3 小节):
\documentclass{memoir}
\usepackage{tabularx}
\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{booktabs}
\NewTableCommand\yes{\SetCell{bg=green9}}
\NewTableCommand\no{\SetCell{bg=red8}}
\begin{document}
\begin{tblr}{cc}
What I want & is below\\
\SetCell{bg=green9} Yes & \SetCell{bg=red8} No\\
\SetCell{bg=green9} Great & \SetCell{bg=red8} Bad\\
What I get & is below\\
\yes Yes & \no No\\
\yes Great & \no Bad
\end{tblr}
\end{document}
答案3
这是 lvjr 的精彩回答(这里,如果您希望我接受,请随意写下您自己的答案),其技巧是使用\expanded
:
\documentclass{memoir}
\usepackage{xcolor}
\usepackage{tabularray}
\NewExpandableDocumentCommand{\yes}{O{Yes}m}{\SetCell{bg=green9}#1}
\NewExpandableDocumentCommand{\no}{O{No}m}{\SetCell{bg=red8}#1}
\begin{document}
\begin{tblr}[expand=\expanded]{cc}
What I want & is below \\
\SetCell{bg=green9} Yes & \SetCell{bg=red8} No \\
\SetCell{bg=green9} Great & \SetCell{bg=red8} Bad \\
What I get & is below \\
\expanded{\yes{}} & \expanded{\no{}} \\
\expanded{\yes[Great]{}} & \expanded{\no[Bad]{}}
\end{tblr}
\end{document}
请注意,您需要使用\unexpanded
命令保护其中的易碎命令(如果有)。