GeneralNeed a simple example of how to make key-value parameters

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
yoyoimut
Posts: 120
Joined: Mon Oct 19, 2009 6:58 am

Need a simple example of how to make key-value parameters

Post by yoyoimut »

Hi everybody,

I need a simple example of how to make key-value parameters.
The scenario I want to do is as follows.

Code: Select all

\documentclass{minimal}

\begin{document}

% Assume I have a command \foo that has 2 optional key-value parameters.
% The explicitly specified parameters will override the defaults.

% Example One: Using the defaults.
\foo{Some Contents}

% Example Two: Override one parameter.
\foo[keyone=valueone]{Some Contents}

% Example Three: Override both parameters.
\foo[keyone=valueone,keytwo=valuetwo]{Some Contents}

\end{document}


Thank you in advance.

regards,

Yoyo
Last edited by yoyoimut on Tue Oct 26, 2010 4:30 pm, edited 1 time in total.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

gmedina
Posts: 2313
Joined: Wed Jul 11, 2007 11:45 pm

Need a simple example of how to make key-value parameters

Post by gmedina »

Hi,

here's an example using xkeyval (the idea: the command \foo{<text>} will create a framed color box enclosing <text>; using two simple (not boolean nor choice) key=value pairs, you can select the frame and background colors):

Code: Select all

\documentclass{article}
\usepackage{xcolor}
\usepackage{xkeyval}

% Declaration of options
\DeclareOptionX<fooexample>{fcolor}{\def\FrameColor{#1}}
\DeclareOptionX<fooexample>{bgcolor}{\def\BGColor{#1}}

% Setting default values
\ExecuteOptionsX<fooexample>{%
  fcolor=red,%
  bgcolor=blue!20
}

% Definition of the command
\newcommand*\foo[2][]{%
  \begingroup
  \setkeys{fooexample}{#1}
  \fcolorbox{\FrameColor}{\BGColor}{#2}
  \endgroup
}

\begin{document}

\foo{Text}

\foo[fcolor=olive!90,bgcolor=red!30]{Some text}

\foo[bgcolor=yellow]{Some test text}

\end{document}
There is a pleyade of packages (there's an article by Joseph Wright comparing three of those packages, but I can't find it right now) to handle key=value declarations : keyval, pgfkeys, and many others.
1,1,2,3,5,8,13,21,34,55,89,144,233,...
yoyoimut
Posts: 120
Joined: Mon Oct 19, 2009 6:58 am

Re: Need a simple example of how to make key-value parameter

Post by yoyoimut »

@gmedina,

Your code helped me.

Thank you so much.


regards,

yoyo
Post Reply