\titlecontents 內的 \if 條件失敗

\titlecontents 內的 \if 條件失敗

我需要toc在某些條件下使用. 在 contentlabel 之前添加一些單字titletoc

\documentclass[]{report}
\usepackage{titlesec, titletoc}

\newif{\ifappendix}


\titlecontents{section}% <section-type>
[2em]% <left>
{}% <above-code>
{\ifappendix \appendixname~\fi\thecontentslabel\ }% <numbered-entry-format>
{}% <numberless-entry-format>
{\titlerule*[0.75pc]{.}\contentspage}% <filler-page-format>\\

\titleformat{\section}[block]
    {\hspace{\parindent}}
    {\ifappendix\appendixname~\fi\thesection}
    {1em}{}    

\begin{document}

\tableofcontents

\section{One}

\appendixtrue

\section{Two}

\end{document}

MWE裡面的條件可以看出\titlecontents,它不起作用(我期望圖片中出現紅色字),但同時它確實可以與\titleformat巨集一起使用。

在此輸入影像描述

答案1

當目錄正在排版時,\ifappendix傳回 false。您還需要傳遞\appendixtrue到該.toc文件。

\documentclass[]{report}
\usepackage{titlesec, titletoc}

\newif{\ifappendix}

\titlecontents{section}% <section-type>
[2em]% <left>
{}% <above-code>
{\ifappendix \appendixname~\fi\thecontentslabel\ }% <numbered-entry-format>
{}% <numberless-entry-format>
{\titlerule*[0.75pc]{.}\contentspage}% <filler-page-format>\\

\titleformat{\section}[block]
    {\hspace{\parindent}}
    {\ifappendix\appendixname~\fi\thesection}
    {1em}{}    

\begin{document}

\tableofcontents

\section{One}

\appendixtrue
\addtocontents{toc}{\protect\appendixtrue}

\section{Two}

\end{document}

在此輸入影像描述

相關內容