How can I use \if \then \else with \@ifclassloaded{}
You can use etoolbox
and its \ifboolexpr
command to combine several conditionals of the form \<conditional [possibly with additional arguments]>{<true>}{<false>}
into one.
Note the test
keyword in front of each conditional and the braces around them.
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\test}{} % just to make sure \test is undefined
\makeatletter
\ifboolexpr{ test {\@ifclassloaded{book}}
or test {\@ifclassloaded{report}}
or test {\@ifclassloaded{memoir}}}
{\def\test{lorem}}
{\def\test{ipsum}}
\makeatother
\begin{document}
\test
\end{document}
In this example you could also directly test for the existence of the \chapter
command. Depending on what you are trying to do that may actually be the better idea.
Here I used \ifundef
from etoolbox
, this reverses the logic from the first example. (There is also \ifdef
, but that treats commands that are \relax
as defined, which isn't that useful for this application.)
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\test}{} % just to make sure \test is undefined
\ifundef\chapter
{\def\test{ipsum}}
{\def\test{lorem}}
\begin{document}
\test
\end{document}
The syntax of \@ifclassloaded
is
\@ifclassloaded{class}{yes code}{no code}
so you do not need \else
. Both branches are built in to the syntax.
You have
\@ifclassloaded{book}
{%
<code block>
}
\makeatother%
so your "no code" argument is \makeatother
so you only execute that if the class is not book.
You should never have \makeatletter
or \makeatother
in a package code anyway so your fragment should look like
\RequirePackage{pgffor}
\@ifclassloaded{book}
{%
<code block>
}{%
else code
}
\@ifclassloaded{article}
{%
<code block>
}{%
else code
}
Incidentally checking for class by name isn't really recommended, there are thousands of classes and if someone makes one by copying book.cls
and changing a few things, your package will not recognise it as a book-like class. It is usually better to test for specific features like \chapter
being defined rather than checking that the class is called book
.