如何在新環境下定義標籤?

如何在新環境下定義標籤?

我想定義一個新的寫作練習環境。此外,我想使用\refand \nameref(帶hyperref包)來建立一個練習編號和名稱表。我寫了以下文件。效果\ref很好(它給了我練習的編號),但\nameref給了我部分的名稱而不是練習的名稱

\documentclass{article}
\usepackage{hyperref}

\newcounter{exo}
\newenvironment{exo}[1]%
{\refstepcounter{exo}\vspace{0.5cm}\noindent
{\begin{large}\bfseries{Exercice \theexo~: #1} \end{large}} \par}
{\par\vspace{0.5cm}}

\begin{document}
A small example

\section{First degree}
\begin{exo}{First degree equation}\label{exo:first_degree}
Solve the equation~:\[ x+7 = -9 \: . \]
\end{exo}

\section{Second degree}
A little harder\ldots

\begin{exo}{Second degree equation}\label{exo:second_degree}
solve the equation~:\[ x^2 - 2x -3 =0 \: . \]
\end{exo}

\begin{exo}{Another exercise}\label{exo:other_exercise}
solve this equation:\[ -3x^2 +7x-64=0 \: .\]
\end{exo}

And here is a table of the exercices:

\begin{tabular}{|c | c|}
\hline
Number & tile \\
\ref{exo:first_degree} & \nameref{exo:first_degree}\\
\ref{exo:second_degree} &\nameref{exo:second_degree}\\
\ref{exo:other_exercise} &\nameref{exo:other_exercise}\\
\hline
\end{tabular}

\end{document}

答案1

\documentclass{article}
\usepackage{hyperref}

\newcounter{exo}
\makeatletter
\newenvironment{exo}[1]%
{\refstepcounter{exo}%
\protected@edef\@currentlabelname{#1}% addition here
\vspace{0.5cm}\noindent
{\large\bfseries{Exercice \theexo~: #1} \par}
{\par\vspace{0.5cm}}}
\makeatother

\begin{document}
A small example

\section{First degree}
\begin{exo}{First degree equation}\label{exo:first_degree}
Solve the equation~:\[ x+7 = -9 \: . \]
\end{exo}

\section{Second degree}
A little harder\ldots

\begin{exo}{Second degree equation}\label{exo:second_degree}
solve the equation~:\[ x^2 - 2x -3 =0 \: . \]
\end{exo}

\begin{exo}{Another exercise}\label{exo:other_exercise}
solve this equation:\[ -3x^2 +7x-64=0 \: .\]
\end{exo}

And here is a table of the exercices:

\begin{tabular}{|c | c|}
\hline
Number & tile \\
\ref{exo:first_degree} & \nameref{exo:first_degree}\\
\ref{exo:second_degree} &\nameref{exo:second_degree}\\
\ref{exo:other_exercise} &\nameref{exo:other_exercise}\\
\hline
\end{tabular}

\end{document}

相關內容