titlesec:仅当有子节时才在标题中显示子节标题

titlesec:仅当有子节时才在标题中显示子节标题

我希望标题左侧显示部分名称,右侧显示子部分名称。只要每个部分都有子部分,这种方法就很好。但是,如果某个部分没有子部分,它就会继续列出上一节的最后一个子部分。

如果当前部分中确实有一个新的子部分,我该如何更改代码以仅显示该子部分?

梅威瑟:

\documentclass[a4paper, 11pt]{article}
\usepackage[pagestyles,extramarks]{titlesec}
\settitlemarks*{section,subsection}
\newpagestyle{mypage}[\small]{%
  \sethead{\firsttitlemarks \sectiontitle}%
  {}%
  {\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}

答案1

titlesec包定义了\ifthechapter, \ifthesection, ...执行该作业的条件:

\documentclass[a4paper, 11pt]{article}
\usepackage[pagestyles,extramarks]{titlesec}
\settitlemarks*{section,subsection}
\newpagestyle{mypage}[\small]{%
  \sethead{\firsttitlemarks \sectiontitle}%
  {}%
  {\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} 

在此处输入图片描述

相关内容