使用样式和默认值初始化 pgfkey(如在对象构造函数中)

使用样式和默认值初始化 pgfkey(如在对象构造函数中)

使用pgfkeys,我想像使用对象构造函数设置属性一样初始化键。

这样我就可以根据的一些初始属性来创建键等/Photo/May,并设置一些默认值。/Photo/June/Photo

显然这应该很容易,但我似乎没有正确解释手册:

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

梅威瑟:

\documentclass{article}

\makeatletter

\usepackage{pgfkeys}

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

% #1 = options, #2 = photo name
\newcommand\SetPhoto[2][]{%
  \pgfkeys{%
    /Photo/#2/.is family, /Photo/#2,
    /Photo/#2/.append style=/Photo/init,
    defaults, file={#2},
    #1%
  }%
}

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

\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}

答案1

明白了!你不需要.append style=/Photo/init,你只需要调用/Photo/init来应用其中设置的样式。

% #1 = options, #2 = photo name
\newcommand\SetPhoto[2][]{%
  \pgfkeys{%
    /Photo/#2/.is family, /Photo/#2,
    /Photo/init,
    defaults, file={#2},
    #1%
  }%
}

因此正确的 mwe 是:

\documentclass{article}

\makeatletter

\usepackage{pgfkeys}

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

% #1 = options, #2 = photo name
\newcommand\SetPhoto[2][]{%
  \pgfkeys{%
    /Photo/#2/.is family, /Photo/#2,
    /Photo/init,
    defaults, file={#2},
    #1%
  }%
}

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

\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}

相关内容