5

In tikz, how can I set a node's contents from a style ?

For example, instead of writing this:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
  \matrix[matrix of nodes] {
    |[name=A-Foo]|A.Foo & |[name=B-Foo]|B.Foo & \dots \\
  };
\end{tikzpicture}
\end{document}

I would like to write this, but the option contents doesn't exist:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
  nc/.style 2 args={name={#1-#2}, content={#1.#2}}
  ]
  \matrix[matrix of nodes] {
    |[nc={A}{Foo}]| & |[nc={B}{Foo}]| & \dots \\
  };
\end{tikzpicture}
\end{document}
3
  • 1
    You can’t really/officially. You can misuse the font key or even better execute at begin cell which may not always work or have downsides as it is executed rather early. Though, in a matrix you can setup the execute at begin cell and execute at end cell in a way which would make this possible. What you also can do is use label=center:{#1.#2} (in fact, this adds another node with that content) but then the actual node doesn’t get re-sized and such things. Sep 13, 2013 at 20:41
  • @Qrrbrbirlbel Thanks, execute at end cell={\node{#1.#2};} seems to do the trick. If you post your comment as an answer, I'll accept it. Sep 13, 2013 at 20:57
  • That should read “or even better execute at begin node” in my previous comment. Sep 13, 2013 at 21:05

1 Answer 1

6

Within a matrix, this can be done with a small fix to the \tikz@lib@matrix@end@cell macro.

The following solution adds the contents of the content key add the end of the node (but not an “empty” node.

Code

\documentclass[tikz]{standalone}
%\usepackage{tikz}
\usetikzlibrary{matrix}
\makeatletter
\def\tikz@lib@matrix@end@cell@{%
  \pgfkeysvalueof{/tikz/content}%
  \iftikz@lib@matrix@plain\else%
    \expandafter\egroup\expandafter;\fi}
\tikzset{
  content/.initial=,
  matrix of nodes with the possibility to set the content/.style={
    matrix of nodes,
    /utils/exec=\let\tikz@lib@matrix@end@cell\tikz@lib@matrix@end@cell@}}
\makeatother
\begin{document}
\begin{tikzpicture}[nc/.style 2 args={name={#1-#2}, content={#1.#2}}]
  \matrix[matrix of nodes with the possibility to set the content] {
    |[nc={A}{Foo}]| & |[nc={B}{Foo}]| & \dots \\
  };
\end{tikzpicture}
\begin{tikzpicture}
\matrix[
   matrix of nodes with the possibility to set the content,
   nodes in empty cells, content={\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn}] {
    & {} & {} & {} & {} \\
 {} &    & {} & {} & {} \\
 {} & {} &    & {} & {} \\
 {} & {} & {} &    & {} \\
 {} & {} & {} & {} &    \\};
\end{tikzpicture}
\end{document}

Output

enter image description here enter image description here

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .