[Tex/LaTex] How to make a tikz node with differently styled text and line breaks

fontsline-breakingtikz-pgf

I am trying to create a tikz node with differently styled text. Adding a line break inside a bold text breaks the rendering with:

! Undefined control sequence.
\tikz@invoke@collected@onpath …mmand \tikz@temp
\pgf@stop \tikz@node@is@a@…
l.14 \testNode{1}{Normal text}{Bold\\text}

This code reproduces the error:

\documentclass[a4paper,landscape]{article}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes.multipart,shapes.geometric,arrows,arrows.meta,calc}
\tikzstyle{theTest} = [font=\small, draw, thin, align=flush center, minimum height=1em, node distance=3em]
\newcommand{\testNode}[3]{
\node[theTest] (#1) {
#2\\
\textbf{#3}
};
}
\begin{document}
\begin{tikzpicture}

\testNode{1}{Normal text}{Bold\\text}

\end{tikzpicture}
\end{document}

Edit: I am looking for a dynamic approach, where I don't know whether "bold text" has or has not a new line.

Best Answer

\\ must not be inside \textbf, because the multi-line feature works similar to a table (tabular, array).

The formatting \textbf{bold\\text} must be applied in both rows:

\textbf{bold}\\\textbf{text}

Full example:

\documentclass[a4paper,landscape]{article}
\usepackage{tikz}
\usetikzlibrary{
  positioning,
  shapes.multipart,
  shapes.geometric,
  arrows,
  arrows.meta,
  calc
}

\tikzstyle{theTest} = [
  font=\small,
  draw,
  thin,
  align=flush center,
  minimum height=1em,
  node distance=3em,
]
\begin{document}
\begin{tikzpicture}

\node[theTest] (1) {
  Normal text\\
  \textbf{bold text}
};

\node[theTest,below of=1] (2) {
  Normal text\\
  %\textbf{bold\\text}
  \textbf{bold}\\
  \textbf{text}
};

\end{tikzpicture}
\end{document}

Result

If the text is provided by a macro with arbitrary contents, then a \parbox or environment minipage can be used. The following example uses environment varwidth, which is able to decrease the width of the overall box, when the lines are shorter than specified:

\documentclass[a4paper,landscape]{article}
\usepackage{varwidth}
\usepackage{tikz}

\tikzstyle{theTest} = [
  font=\small,
  draw,
  thin,
  align=flush center,
  minimum height=1em,
  node distance=3em,
]
\begin{document}
\begin{tikzpicture}

\newcommand\mymacro{Normal text\\\textbf{bold\\text}}

\node[theTest] (1) {%
  \begin{varwidth}{.2\linewidth}% maximum width
    \centering
    \mymacro
  \end{varwidth}%
};

\end{tikzpicture}
\end{document}

Result with varwidth