TransWikia.com

Using RequirePackage with parameters

TeX - LaTeX Asked on June 8, 2021

I want to outsource my preamble to a different file. So far I’m doing it with RequirePackage. This ends up looking like this:

RequirePackage{templates}
begin{document}
...
end{document}

My templates file contains everything else and can be an abitrary preamble. Now I want to use a parameter (string) for RequirePackage which I can use in the template file. Normally I would do it like this: RequirePackage[Parameter] and then use it with #1. This does not work and I couldn’t find a website or post that has an answer. Can you help me?

One Answer

What you are asking about is basic package writing. You cannot (not with usepackage at least) refer to options with #1 and #2, you have to use LaTeX's option machinery. Here's an example to get you started (I wrapped the example package in the filecontents environment to keep the example self-contained):

begin{filecontents}{templates.sty}
% Declare the conditional and the option
newififParameter
DeclareOption{Parameter}{Parametertrue}

% Process the options
ProcessOptions

% Do something with the processed conditional
ifParameter
  newcommandsomecommand{With option Parameter}
else
  newcommandsomecommand{Without option Parameter}
fi
end{filecontents}
documentclass{article}
usepackage[Parameter]{templates}
begin{document}
somecommand
end{document}

The example above prints With option Parameter.


The first two lines create a conditional ifParameter (which is false by default) and the DeclareOption line creates an option called Parameter which sets the ifParameter conditional to true (by using Parametertrue):

newififParameter
DeclareOption{Parameter}{Parametertrue}

Then you use ProcessOptions to process the options given to the package against the ones declared in the package code, and finally you use ifParameter .. else .. fi to execute some code conditionally.


The syntax of DeclareOption is:

DeclareOption{<option>}{<code>}

where <option> is the option name and <code> is whatever code you want executed when that option is given to the package. Additionally you may use

DeclareOption*{<default code>}

then the <default code> will be used for any option that was not explicitly declared (in <default code>, the option used is stored in CurrentOption).

Correct answer by Phelype Oleinik on June 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP