I want to load data from a file and use it in a figure caption. Found this code (that I've modified slightly to demonstrate it's limitations) which does exactly what I want it to do when it works, for example in the math environment. But it doesn't work at all in a figure caption or section title. Is there anyway to resolve this issue?
\documentclass{article}
\usepackage{datatool, filecontents}
\DTLsetseparator{ = }
\begin{filecontents*}{mydata.dat}
foo = 10
bar = 20
\end{filecontents*}
\begin{document}
\DTLloaddb[noheader, keys={thekey,thevalue}]{mydata}{mydata.dat}
\newcommand{\mycommand}[1]{\DTLfetch{mydata}{thekey}{#1}{thevalue}}
%This works
The first value \mycommand{foo} and the second value $\mycommand{bar}$.
%This doesn't
\section{\mycommand{foo}}
%Nor this
\begin{figure}
\caption{And some parameter has the value \mycommand{foo}}
\end{figure}
\end{document}


\protect\mycommand– David Carlisle Mar 11 '20 at 10:20