我如何将可选参数传递给在 之后部分绘制的节点\newenvironment*
?在 之前部分这很容易,因为我可以简单地使用#1
。我尝试使用\edef
,但结果如下:
!包 pgfkeys 错误:我不知道密钥“/tikz/draw=red”,我将忽略它。也许你拼错了。
\documentclass[tikz,convert]{standalone}
\newenvironment*{verycontrivedexample}[1][]
{
\node [draw=black, #1] (Before) at (0, 1) {Before};
}
{
% This is what I'd like to do, but #1 is not available anymore
% \node [draw=black, #1] (After) at (0, 0) {After};
}
\begin{document}
\begin{tikzpicture}
\begin{verycontrivedexample}[draw=red]
\end{verycontrivedexample}
\end{tikzpicture}
\end{document}
答案1
引用为什么环境的结束代码不能包含参数?你需要存储#1
“结束”部分。通常这由辅助宏完成:
\newenvironment*{verycontrivedexample}[1][]
{
\node [draw=black, #1] (Before) at (0, 1) {Before};
\def\optargument{#1}% Store optional argument for later use.
}
{
\node [draw=black, style/.expand once=\optargument] (After) at (0, 0) {After};
}
键style
用于扩展\optargument
回其内容(否则大多数情况下您最终会得到类似的结果I do not know the key '/tikz/draw=red'
)。
仅使用样式就可以完成相同的操作,基本上使用相同的方法:
\newenvironment*{verycontrivedexample}[1][]
{
\node [draw=black, #1] (Before) at (0, 1) {Before};
\tikzset{opt argument/.style={#1}}% Store optional argument for later use.
}
{
\node [draw=black, opt argument] (After) at (0, 0) {After};
}
在这两种情况下,环境用户都可以访问宏\optargument
或样式,无意或有意地更改/覆盖内容(使用样式很容易,使用宏稍微困难一些)。opt argument
\documentclass[tikz,convert]{standalone}% http://ctan.org/pkg/standalone
\newenvironment*{verycontrivedexample}[1][]
{
\node [draw=black, #1] (Before) at (0, 1) {Before};
\def\optargument{#1}% Store optional argument for later use.
}
{
\node [draw=black, style/.expand once=\optargument] (After) at (0, 0) {After};
}
\begin{document}
\begin{tikzpicture}
\begin{verycontrivedexample}[draw=red]
\end{verycontrivedexample}
\end{tikzpicture}
\end{document}
答案2
您xparse
也可以参考以下部分中的参数\end
:
\documentclass[tikz]{standalone}
\usepackage{xparse}
% O{} means "optional argument with empty default"
\NewDocumentEnvironment{verycontrivedexample}{O{}}
{\node [draw=black, #1] (Before) at (0, 1) {Before};}
{\node [draw=black, #1] (After) at (0, 0) {After};}
\begin{document}
\begin{tikzpicture}
\begin{verycontrivedexample}[draw=red]
\end{verycontrivedexample}
\end{tikzpicture}
\end{document}