[Tex/LaTex] Different \section for odd and even pages

conditionalsdouble-sidedpage-numberingsectioning

I would like to make the section titles look different on even and odd pages. I have the following MnWE with the trivial approach. The problem is that you don't know that your section header gets moved to the next page. I even tried to check the oddity of the page number after the section is typeset, but with no success (that is the "After:" text).

\documentclass[a4paper,twoside]{article}

\makeatletter
\let\X@section\section
\def\section#1{%
  \ifodd\c@page\relax
    \X@section{ODD: #1}%
  \else
    \X@section{EVEN: #1}%
  \fi
  \par After:\ifodd\c@page\relax odd\else even\fi \par % <-- for testing purposes
}
\makeatother

\usepackage{lipsum}

\begin{document}

\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]
\section{Test section} \lipsum[1]

\end{document}

Best Answer

Try using the titlesec package. The command \titleformat included in it can take an page=odd or page=even option to give different formatting depending on even or odd page numbers, just like you want.


\usepackage{titlesec}
\titleformat{name=\section,page=odd}{}{ODD:}{.5em}{}
\titleformat{name=\section,page=even}{}{EVEN:}{.5em}{}

in the preamble should give what you want.