如何将宏的内容解释为 pgfkeys 的 key=value 赋值

如何将宏的内容解释为 pgfkeys 的 key=value 赋值

基于这个 pgfkeys 方法,我尝试将选项收集到宏中以供以后重复使用:

% Set options for a photo
% #1 = options, #2 = photo name, i.e. June
\newcommand\SetPhoto[2][]{%
  \expandafter\def\csname #2photoOptions\endcsname{#1}%
}

\pgfkeys{
  /Photo/.is family, /Photo,
    defaults/.style = {bleed = 0pt,},
    bleed/.initial = {},
}

% Place the photo using eariler options
% #1 = photo name
\newcommand\DoPhoto[1]{%
  \pgfkeys{
    /Photo, defaults,
    \csname #1photoOptions\endcsname,
  }%

  % ...
  % ... deal with placing the photo, \includegraphics and so on
  % ...
}

像这样使用它:

% somewhere early in the document
\SetPhoto[bleed=3mm]{June}
\SetPhoto[bleed=5mm]{July}

% typeset the photos with the given options 
\DoPhoto{June}
\DoPhoto{July}

但是 pgfkeys 将宏 ( bleed=3mm) 的整个内容视为键:

! Package pgfkeys Error: I do not know the key '/Photo/bleed=3mm' and I am going to ignore it. Perhaps you misspelled it.

如何将宏的内容解释为键=值赋值?

答案1

您要么必须使用任意\expandafter,\edef组合来扩展定义中的控制序列,要么使用按键来执行所有操作。由于控制序列包含样式按键,因此定义宏毫无意义。相反,请使用按键系统并将选项转储到样式中:

\newcommand*\SetPhoto[2][]{\pgfkeys{/Photo/#2photoOptions/.style={#1}}

然后当你有

\newcommand*\DoPhoto[1]{\pgfkeys{/Photo, defaults,#1photoOptions}}

或此定义的扩展版本。

答案2

根据 percusse 的回答:

\documentclass{article}

\makeatletter

\usepackage{pgfkeys}

\pgfkeys{
  /Photo/.is family, /Photo,
    defaults/.style = {bleed = 0pt,},
    bleed/.initial = {},
}

\newcommand\SetPhoto[2][]{\pgfkeys{/Photo/#2opts/.style={#1}}}

\newcommand\DoPhoto[1]{%
  \pgfkeys{/Photo, defaults, #1opts}%
  % suppose it was an image...
  \hskip -\pgfkeysvalueof{/Photo/bleed}%
  \frame{#1}%
}

\setlength{\parskip}{0pt}%
\setlength{\parindent}{0pt}%

\makeatother

\begin{document}

% somewhere early in the document
\SetPhoto{May}%
\SetPhoto[bleed=3mm]{June}%
\SetPhoto[bleed=5mm]{July}%

% typeset the photos with the given options 

\DoPhoto{May}

\DoPhoto{June}

\DoPhoto{July}

\end{document}

照片占位符

相关内容