检查 pgfkey 的值

检查 pgfkey 的值

我需要能够检查 pgfkey 的值是否为空。我尝试过的解决方案(使用包etoolbox):

\edef\temp{\pgfkeysvalueof{/path/key}}%
\expandafter\ifstrequal\expandafter{\temp}{}{key is empty}{key is not empty}%

但是如果键的值扩展为空或更糟,则此方法不起作用:键的值无法扩展!如何在不扩展键的情况下检查键是否为空?我只想检查它的字符串值是否等于“”。

编辑:添加了一个完整的示例

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\usepackage{overpic}

\newcommand{\strcomp}{\expandafter\ifstrequal\expandafter}%

\pgfkeys{
    /icon/.cd,
    width/.initial,
    overlay/.initial,
}

\newcommand{\icon}[2][]{%
    {%
        \pgfkeys{/icon/.cd,width,overlay,#1}%
        \def\options{}%
        \edef\temp{\pgfkeysvalueof{/icon/width}}%
        \strcomp{\temp}{}{}{\edef\options{width=\pgfkeysvalueof{/icon/width},\options}}%
        \edef\temp{\pgfkeysvalueof{/icon/overlay}}%
        \strcomp{\temp}{}{%
            \edef\graphic{\noexpand\includegraphics[\options]{#2}}%
        }{%
            \edef\temp{\noexpand\begin{overpic}[\options]{#2}}%
            \def\graphic{\temp\put(0,0){\pgfkeysvalueof{/icon/overlay}}\end{overpic}}%
        }%
        \graphic
    }%
}%

\begin{document}

\icon{example-image} % Works!
\icon[width=3cm]{example-image} % Works :)
\icon[width=3cm,overlay=jei]{example-image} % Also works :)
\icon[width=3cm,overlay={\includegraphics{overlay-image}}]{example-image} % Breaks down when trying to expand in \edef\temp{\pgfkeysvalueof{/icon/overlay}}

\end{document}

答案1

当未设置键时,值是\pgfkeysemptyvalue,因此您需要将值与此进行比较。一种方法是使用\ifdefequal

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\usepackage{overpic}


\pgfkeys{
    /icon/.cd,
    width/.initial,
    overlay/.initial,
}

\newcommand{\icon}[2][]{%
    {%
        \pgfkeys{/icon/.cd,width,overlay,#1,width/.get=\temp}%
        \def\tempa{\pgfkeysnovalue}
        \def\options{}%
        \ifdefequal{\temp}{\tempa}{}{\edef\options{width=\temp,\options}}%
        \pgfkeysgetvalue{/icon/overlay}{\temp}%
        \ifdefequal{\temp}{\tempa}{%
            \edef\graphic{\noexpand\includegraphics[\options]{#2}}%
        }{%
            \edef\temp{\noexpand\begin{overpic}[\options]{#2}}%
            \def\graphic{\temp\put(0,0){\pgfkeysvalueof{/icon/overlay}}\end{overpic}}%
        }%
        \graphic
    }%
}%

\begin{document}

\icon{example-image}

\icon[width=3cm]{example-image}

\icon[width=3cm,overlay=jei]{example-image}

\icon[width=3cm,overlay={\includegraphics{example-image-a}}]{example-image}

\end{document}

相关内容