9

How do I insert the title in the footer? And decide if it is set or not?

%preteste.sty
\usepackage{fancyhdr}
\usepackage{lipsum}

\renewcommand{\title}[1]{\gdef\@title{#1}\gdef\mytitle{#1}}
\newcommand{\mytitle}{%
   \PackageErrorNoLine{pkgname}
     {No \protect\title\space given}
     {You have to provide a title}%
   \gdef\mytitle{You have to provide a title}%
   \mytitle
}
\fancyfoot{}
\fancyfoot[C]{\mytitle}

See the error if no define \title and no use \maketitle

%titulo.tex
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{preteste}

% \title{Title}
% \author{R\'egis S. Santos}
% \date{\the\year}

\begin{document}
\pagestyle{fancy}
% \maketitle

\lipsum
\end{document}

fix my code, please.

Regis Santos
  • 14,463
  • 2
    related/possible duplicates: http://tex.stackexchange.com/questions/27710/how-can-i-use-author-date-and-title-after-maketitle, http://tex.stackexchange.com/questions/10130/use-the-values-of-title-author-and-date-on-a-custom-title-page – doncherry Oct 09 '11 at 23:23

2 Answers2

11

After \maketitle the title is forgotten. By the way, \title wouldn't print the title anyway: it's a command for declaring what the title is.

\newcommand{\mytitle}{Title}
\title{\mytitle}
...
\fancyfoot[C]{\mytitle}

If you need it in a package, then redefine \title:

\renewcommand{\title}[1]{\gdef\@title{#1}\gdef\mytitle{#1}}
...
\fancyfoot[C]{\mytitle}

This duplication will allow you to say normally

\title{Title}
\author{A. U. Thor}
\maketitle

in the document.

If you want to raise an error if the author doesn't provide a \title declaration, add to your package

\newcommand{\mytitle}{%
   \PackageError{preteste}% use the package name
     {No \protect\title\space given\@gobble}
     {You have to provide a title}%
   \gdef\mytitle{You have to provide a title}%
   \mytitle}

After raising the error, it will redefine itself to print an informative message in the footer. The \title declaration in the document will clear this definition, so there's nothing to worry about.

The titling package can be used, but maybe it's too much for this simple application.

egreg
  • 1,121,712
2

I think an easy solution involves the following instructions in the document's preamble after the \title, \author, and \date commands have been set up:

\makeatletter
\let\doctitle\@title
\makeatother

You can then insert the title string in the footer as follows:

\fancyfoot[C]{\doctitle}

Finally, if you want to put all of this stuff in a package, be sure to invoke this package only after the \title has been set up and the fancyhdr package has been loaded. Happy TeXing!

Mico
  • 506,678