\nameref{} 没有引用正确的标签 x titlesec

\nameref{} 没有引用正确的标签 x titlesec

我正在使用 hyperref 包进行交叉引用,但遇到了一些问题,它与有关\usepackage{titlesec,titleps},例如:

\documentclass[a4paper,12pt,twoside]{report}
\usepackage{hyperref}
\usepackage{titlesec,titleps} %If I remove the \titleclass for \part it works fine!
\titleclass{\part}{top}\titleformat{\part}{\centering\normalfont\Huge\bfseries}{}{0pt}{}
\titleformat{\section}{\normalfont\bfseries}{\thesection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\subsection}{\normalfont\slshape}{\thesubsection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\subsubsection}{\normalfont}{\thesubsubsection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\paragraph}{\normalfont\slshape}{\theparagraph\hspace{3pt}$\vert$}{3pt}{}{}
\titleformat{\subparagraph}{\normalfont}{\thesubparagraph\hspace{3pt}$\vert$}{3pt}{}{}

\begin{document}
\part{Part One}
\label{P1}
\chapter{Chapter One}
\label{C1}
\section{Section One}
\label{S1}
Here the cross-reference for \autoref{C1} "\nameref{C1}" and \autoref{S1} "\nameref{S1}" work fine, but not for \autoref{P1} "\nameref{P1}".

As also for \autoref{C2} "\nameref{C2}" and \autoref{S2} "\nameref{S2}", but not for \autoref{P2} "\nameref{P2}".\\

\part{Part Two}
\label{P2}
\chapter{Chapter Two}
\label{C2}
\section{Section Two}
\label{S2}

\end{document}

因此,如果我在“第一部分”的任何地方交叉引用,\nameref{P2}它都会给出“第一节”的名称(第二部分之前的最后一节,如果我删除该节,它会转到它之前的一节),而“第二部分”是\autoref{P2}正确的。如果我在“第一部分”中引用, \nameref{P1}它会给出错误“??”。 有没有办法知道发生了什么事?感谢您的帮助和关注!

答案1

不确定哪个包破坏了什么,但\part最终没有以可以使用的形式保存部件名称nameref。这只是重新定义它以明确保存它,它假设您不需要*[]参数形式\part

\documentclass[a4paper,12pt,twoside]{report}

\usepackage{titlesec,titleps} %If I remove the \titleclass for \part it works fine!
%\titleclass{\part}{top}\titleformat{\part}{\centering\normalfont\Huge\bfseries}{}{0pt}{}
\titleformat{\section}{\normalfont\bfseries}{\thesection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\subsection}{\normalfont\slshape}{\thesubsection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\subsubsection}{\normalfont}{\thesubsubsection\hspace{3pt}$\vert$}{3pt}{}
\titleformat{\paragraph}{\normalfont\slshape}{\theparagraph\hspace{3pt}$\vert$}{3pt}{}{}
\titleformat{\subparagraph}{\normalfont}{\thesubparagraph\hspace{3pt}$\vert$}{3pt}{}{}
\usepackage{hyperref}
\makeatletter
\let\oldpart\part
\def\part#1{\def\@currentlabelname{#1}\oldpart{#1}}
\makeatother
\begin{document}
\part{Part One}
\label{P1}
\chapter{Chapter One}
\label{C1}
\section{Section One}
\label{S1}
Here the cross-reference for \autoref{C1} "\nameref{C1}" and \autoref{S1} "\nameref{S1}" work fine, but not for \autoref{P1} "\nameref{P1}".

As also for \autoref{C2} "\nameref{C2}" and \autoref{S2} "\nameref{S2}", but not for \autoref{P2} "\nameref{P2}".\\

\part{Part Two}
\label{P2}

\chapter{Chapter Two}
\label{C2}
\section{Section Two}
\label{S2}

\end{document}

相关内容