# titlesec: display subsectiontitle in header only if there is a subsection

I want to have my header as the section name displayed on the left and the subsection name displayed on the right. This works well as long as every section has a subsection. However if there is no subsection in a section, it keeps listing the last subsection from an previous section.

How can I change my code to have only a subsection displayed if there actually is a new subsection in the current section?

MWE:

\documentclass[a4paper, 11pt]{article}
\usepackage[pagestyles,extramarks]{titlesec}
\settitlemarks*{section,subsection}
\newpagestyle{mypage}[\small]{%
{}%
{\firstextramarks{subsection}\thesubsection.~\subsectiontitle}%
\setfoot{}%
{\thepage}%
{}%
}
\pagestyle{mypage}

\begin{document}
\section{First section}
This section should not have a subsection in the header.
\newpage
\section{Second section}
\subsection{Test}
This section should have a subsection in the header.
\newpage
\section{Third section}
This section should not have a subsection in the header.
\end{document}


The titlesec package defines conditionals \ifthechapter, \ifthesection, ... which do the job:

\documentclass[a4paper, 11pt]{article}
\usepackage[pagestyles,extramarks]{titlesec}
\settitlemarks*{section,subsection}
\newpagestyle{mypage}[\small]{%
{}%
{\ifthesubsection{\firstextramarks{subsection}\thesubsection.~\subsectiontitle}{}}%
\setfoot{}%
{\thepage}%
{}%
}
\pagestyle{mypage}

\begin{document}

\section{First section}
This section should not have a subsection in the header.
\newpage
\section{Second section}
\subsection{Test}
This section should have a subsection in the header.
\newpage
\section{Third section}
This section does not have a subsection in the header.

\end{document}


• Exactly what I was looking for (and for some reason couldn't find in the documentation). Thanks alot! – Shakaja Jun 10 at 21:23
• You're welcome! – Bernard Jun 10 at 21:35