
我目前正在編寫我的第一個文檔類文件(個人化簡歷類),我想更好地了解我到底在做什麼。所以,現在我正在設定允許將值分配給變數的命令(不確定這是否真的是我應該使用的單字),透過以下結構:
\newcommand{\institution}[1]{\def\@institution{#1}}
\newcommand{\datesattended}[1]{\def\@datesattended{#1}}
\newcommand{\degree}[1]{\def\@degree{#1}}
因此,在 .tex 檔案中,使用者可以使用該命令\institution{University of Whatever}
將字串「University of Whatever」儲存到\@institution
,然後由另一個命令在類別檔案中呼叫該字串。
所有這些都按我想要的方式工作,但現在我希望創建一些條件表達式來控制輸出。例如,我有一個命令\education
,當在文件中呼叫時,將根據使用者已輸入的機構名稱、就讀日期、學位資訊等來格式化履歷的教育部分。我希望能夠在類別文件中進行設定以檢查這些\@variable
變數是否已定義,然後根據定義的變數和空的變數以不同的方式格式化輸出。
首先,我認為我的許多問題是我實際上並不理解這些\@variable
定義是什麼或我可以用它們做什麼的範圍。
我想要實現的完整範例如下(在 LaTeX/pseudo 中):
\newcommand{\showeducation}{%
\@institutionname -- \@degree
if \@datesattended is defined:
\newline \@datesattended
clear \@institutionname, \@datesattended, \@degree
}
因此,如果\@datesattended
定義了,格式將更改以適應它。否則,命令將直接跳過它,並列印給出的信息。
答案1
命令沒有什麼特別的\@variable
。它們只是宏,用於儲存內容而不是執行其他操作。因此,可以透過使用 \ifdefined
(e-TeX) 原語來測試是否已定義。
\documentclass[11pt,a4paper]{article}
\makeatletter
\newcommand{\@institutionname}{Ministry of Silly Walks}
\newcommand{\@degree}{Minster of Silly Walks}
%\newcommand{\@datesattended}{1969}
\newcommand{\showeducation}{%
\@institutionname\ -- \@degree
\ifdefined\@datesattended
\newline \@datesattended % Please use some 'better' setup here
\else
\let\@institutionname\relax
\let\@datesattended\relax
\let\@degree\relax
\fi
}
\makeatother
\begin{document}
\showeducation % Date should not be printed
\makeatletter
\newcommand{\@datesattended}{1969}
\makeatother
\showeducation % Now it should be printed, but the rest is \relax`ed
\end{document}
編輯\ifdef
使用frometoolbox
包應該可以達到相同的效果
答案2
也許比\newcommand[1]...
使用 toks 暫存器更好:
\newtoks\institution \newtoks\datesattended \newtoks\degree
如果用戶說
\institution{Ministry of Silly Walks}
那麼您可以在巨集中使用該值,如下所示:
\the\institution
如果您需要測試“變數”的值是否已設置,您可以執行以下操作:
\if\relax\the\degree\relax The degree isn't set.\else The degree is set.\fi