A conditional named \iftex4ht
is impossible to define without side effects. However using directly \@ifpackageloaded{tex4ht}
has a big limitation, because it's allowed only in the preamble.
There are a few strategies to circumvent the problem: all use \@ifpackageloaded
in the preamble to define something that one will be able to use also in the body of the document.
Primitive conditional syntax
\makeatletter
\@ifpackageloaded{tex4ht}
{\let\iftexforht\iftrue}
{\let\iftexforht\iffalse}
\makeatother
and use \iftexforht
just like any of the primitive conditionals.
LaTeX pseudoconditional
\makeatletter
\@ifpackageloaded{tex4ht}
{\let\iftexforhtTF\@firstoftwo}
{\let\iftexforhtTF\@secondoftwo}
\makeatother
to be used like
\iftexforhtTF{<code for TeX4ht>}{<code when TeX4ht isn't used>}
Almost like a primitive conditional
\makeatletter
\edef\texforht{TT\noexpand\fi
\@ifpackageloaded{tex4ht}
{\noexpand\iftrue}
{\noexpand\iffalse}}
\makeatother
to be used as
\if\texforht
<code for TeX4ht>
\else
<code when TeX4ht isn't used>
\fi
Which one to prefer is a matter of taste. Both the first and third methods allow conditional nesting.
Prompted by extra \fi error when using \localtableofcontents inside an \if...\else..\fi, there is another reason for using the LaTeX conditional style (case 2 in the list above).
When used in the preamble, a construction such as
\iftexforht
<code for TeX4ht case>
\else
<code for non TeX4ht case>
\fi
is usually good and practical. However when used in the document body, you can incur in problems. For instance, if you have
\iftexforht\else\localtableofcontents\fi
as in the linked question, this won't work and throw a mysterious error message, because of how \localtableofcontents
is defined. Instead,
\iftexforhtTF{}{\localtableofcontents}
would have worked properly.
The \iftexforhtTF
macro can be defined either with the code above or, with Nasser's idea,
\makeatletter
\ifdefined\HCode
\let\iftexforhtTF\@firstoftwo
\else
\let\iftexforhtTF\@secondoftwo
\fi
\makeatother
Credit to karlkoeller for spotting the problem in the linked question.