我想从文件加载数据并将其用于图片标题。找到这代码(我稍作修改以展示它的局限性)在工作时完全符合我的要求,例如在数学环境中。但它在图形标题或章节标题中根本不起作用。有什么办法可以解决这个问题吗?
\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}
答案1
\protect\mycommand
定义的命令很脆弱,因此在移动参数(例如\section
或 )中使用时需要使用\caption
。
答案2
readarray
/方法listofitems
效果很好。
\documentclass{article}
\usepackage{readarray}
\begin{filecontents*}{mydata.dat}
foo = 10
bar = 20
\end{filecontents*}
\newcommand\mycommand[1]{\csname keydata#1\endcsname}
\begin{document}
\readarraysepchar{;}
\readdef{mydata.dat}\mydata
\setsepchar{;/=}
\ignoreemptyitems
\readlist*\myrecords{\mydata}
\foreachitem\z\in\myrecords[]{%
\expandafter\xdef\csname keydata\myrecords[\zcnt,1]\endcsname{%
\myrecords[\zcnt,2]}%
}
%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}
如果您需要保留未扩展的关键数据,只需稍微努力一下就可以得到以下结果:
\documentclass{article}
\usepackage{readarray}
\usepackage[T1]{fontenc}
\begin{filecontents*}{mydata.dat}
foo = 10
bar = 20
foomac = \today
\end{filecontents*}
\newcommand\mycommand[1]{\csname keydata#1\endcsname}
\begin{document}
\readarraysepchar{;}
\readdef{mydata.dat}\mydata
\setsepchar{;/=}
\ignoreemptyitems
\readlist*\myrecords{\mydata}
\foreachitem\z\in\myrecords[]{%
\expandafter\def\csname keydata\myrecords[\zcnt,1]\expandafter\expandafter
\expandafter\endcsname\expandafter\expandafter\expandafter{%
\myrecords[\zcnt,2]}%
}
%This works
The first value \mycommand{foo} and the second value $\mycommand{bar}$.
Key value3 is not pre-expanded:
\detokenize\expandafter{\keydatafoomac}.
%This doesn't
\section{\mycommand{foo}}
%Nor this
\begin{figure}
\caption{And some parameter has the value \mycommand{foo}}
\end{figure}
\end{document}