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}
  • 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. – Qrrbrbirlbel Sep 13 '13 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. – Suzanne Dupéron Sep 13 '13 at 20:57
  • That should read “or even better execute at begin node” in my previous comment. – Qrrbrbirlbel Sep 13 '13 at 21:05
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.