## Sunday, October 6, 2013

### LaTeX Tip: How to define variable like \subtitle{...} which can be used from the preamble

Quite often when working with LaTeX, it is quite convenient to be able to define things like subtitles and/or other extra fields to be included in the title section, as per the screenshot below:

Now, before we go any further, I should mention that I am aware of the existence of ready-made custom document classes out there in the wild which often provide the necessary bits and pieces already. But, for argument sake, let's say that we want to keep things lightweight (i.e. fewer deps on external packages) or want to know how to do this in future should the need arise.

A First Attempt - (NOT RECOMMENDED)
An initial attempt at doing this may look something like this...

In your articleTitle.sty file (or some other include):

\newcommand{\subtitle}{}         % 1) How the "field" gets defined
...
{\large \textit{\subtitle}}      % 2) How it gets displayed

In your document, you'd then have to do:

\renewcommand{\subtitle}{My new subtitle text}

As can be seen, while this approach is functional, it is not exactly that syntactically nice, especially since we cannot use this subtitle field in a "native" way like we can with the regular \title and \author fields.

Second Attempt - (RECOMMENDED)
After a lot of searching, I finally stumbled across the following gem by inspecting the sources for one of the document classes in the KOMA-Script package, which provides this field.

% 1) To define the subtitle field...
\newcommand*{\subtitle}[1]{\gdef\@subtitle{#1}}
\newcommand*{\@subtitle}{}%

...

% 2) To use the subtitle field...
{\large \textit{\@subtitle}}

In your document, you can then do:

\subtitle{My new subtitle text}