Template Management

This is an excerpt of the book “Better Books with LaTeX.” The book comes with a LaTeX template you can use to easily create your own books.

Previously, we have covered mainly the chapter folder main, the front folder, and the back folder. Now we will discuss those folders again in more detail and go through the remaining folders. This will help you to know where the configuration for each part of the template lies and allow you to make changes.

  Template Library Files

Let us first focus on the lib directory. There, each file is a set of new commands or configurations to set up the style and contents of your book.

  Packages File

The lib/packages.tex file loads all the libraries in the directory and loads and sets up additional packages, depending on the output format. The first two commands load the nag package to provide additional warnings if you are using outdated or invalid packages, and expand the output of error messages (\errorcontextlines 1000) in the log file to help you fix issues more quickly.

The ifxetex package loads a small script that we can use to check whether the target platform is a printed PDF (with XeLaTeX) or an HTML file (with pdfLaTeX). It follows the basic format of “\ifxetex(executed if XeLaTeX is used) \else (executed if pdfLaTeX is used) \fi.”

Think of \ifxetex as the main junction between the e-book (the HTML file output using pdfLaTeX) and the print book (the PDF file output using XeLaTeX).

Next are a number of packages and configurations specific for either of those platforms. The adjustbox packages adjust figures to fit onto a page—a feature needed only for the printed PDF as e-books automatically adjust graphics depending on the reader. The psvectorian package allows us to add curly horizontal lines at the end of sections and chapters—a feature not supported by e-books. The next command, \hrule, is not supported by tex4ht, so we create a specific command, \myrule, and translate it into a HTML ¡hr /¿ command correspondingly. For the em dash, we need to add spaces (even if it is just 0) left and right of it to allow for line breaks. For the HTML output, we simply use the ASCII code for the em dash (#8212;).

At the end of the file, all relevant packages of the lib directory are loaded, so we only need to include lib/packages.tex to load the whole configuration. On the following pages, I will discuss each package.

 Language Selector

In an Overleaf project, you can select the language by making either german.tex or english.tex the main file. In the file, either the command \babelDE or \babelEN get activated by the command “\usepackage[ngerman]{babel}” or “\usepackage[american]{babel} respectively. The command sets “\languagename” either to “ngerman” or “american.” In lib/languageselector.tex, the new command “\babelDE{content}” checks whether “ngerman” is set, and then displays the content. If it is not set, nothing is displayed. Likewise with the “\babelEN{content}” command, resulting in only one of the languages being displayed. The first use of this command can be seen at the end of the file, where we overwrite the naming of the table of contents depending on the language we have selected.

If you want to add a different language, simply add a new empty TEX file in the root directory (for example, spanish.tex), copy and paste the contents of english.tex into that new file, and replace “american” with “spanish.” Next, add the following commands in lib/languageselector.tex and you are ready to use “\babelES” as a command in your text.

\newcommand{\babelES}[1]{\ifnum\pdfstrcmp{\languagename}{spanish}=0 {#1}\fi} 


Let us start with lib/bibliography.tex. This adds the bibliography feature to the document and (due to compatibility issues) either loads biblatex or natbib depending on whether you use XeLaTeX or pdfLaTeX. In addition, it loads the actual bibliography file from the bibliography directory, depending on the language you have set up.

The parameters of loading biblatex determine what citations look like. There are numerous possible combinations of the author name, the year of publication, and the title, each with different degrees of detail and verbosity. The setting authortitle in my template replaces citations with the author name followed by the title. Without the setting, the default would be a simple number that is referenced again at the back of the book in the bibliography.

At the end, the file also loads the nameref library. With it, you can reference the label of a chapter or section and get the chapter or section title in return. Instead of just referencing an abstract chapter number, adding the title helps the reader to know what you are talking about. In addition, any changes of the referenced chapter or section title are automatically synchronized.

For example, look at this code:

\chapter{My First Chapter}\label{c1_myfirstchapter:sec} 
Yesterday, I bought a car. 
\chapter{My Second Chapter}\label{c2_mysecondchapter:sec} 
In chapter ‘‘My First Chapter,’’ we have talked about buying a car.

If we changed the chapter title “My First Chapter” to “How I Bought My Car,” we would have to update the reference in the second chapter. With the \nameref{} command, this is no longer necessary:

\chapter{My First Chapter}\label{c1_myfirstchapter:sec} 
Yesterday, I bought a car. 
\chapter{My Second Chapter}\label{c2_mysecondchapter:sec} 
In chapter~\ref{c1_mychapter:sec}, we have talked about buying a car.

As we will later discuss in Chapter 13, it is important to prevent duplication of text whenever possible because the larger the document gets, the harder is to apply non-breaking changes. If you have to search through the whole document every time you apply a change, your project will take much longer than necessary.

 Book Format

Next in line is lib/bookformat.tex. The first thing you notice is the long list of usepackage commands with the one marked with 5.25” x 8” uncommented. Here is your choice of how large your book should be. This of course applies only to a printed version of your book. For e-books, the size of your book is determined by the device your reader will use.

Personally, I like 5.25” x 8”, but it is totally up to you. Look at your personal library (and take a ruler) and check out the different formats. Besides personal preference, the only thing to keep in mind is that smaller formats lead to more pages if you do not also reduce the font size (which is not recommended!). Amazon KDP supports all those formats, but if you decide to have the PDF printed by your local printer, first check which formats your printers supports, otherwise you might have to do some redesigning.

\usepackage[paperwidth=13.34cm, paperheight=20.32cm, inner=0.80in, outer=0.3in, top=0.7in, bottom=0.5in]{geometry} % 5.25’’ x 8’’

Looking at the \usepackage[…]{geometry} command itself, you see the self-explanatory paperwidth and paperheight parameters, as well as four parameters to determine the space between the margins of the book and your text. Instead of parameters that determine left and right margin, you see the parameters inner and outer. Given the way books are bound, the inner margin needs to be significantly larger to account for the joint of the book. If the inner margin were as small as the outer margin, the reader would have difficulties reading the book. In addition, printers are not 100% accurate, so you need to keep some safe space to account for printing errors.

The parameters as defined in the file work nicely for my books. Feel free to experiment with different settings, but make sure you keep them within the range the printing company (be it Amazon or another provider) has defined.

Did you know?

Why choose 5 x 8? Ratios like 5 x 8 are commonly found throughout nature. We find them appealing because our own perception is “calibrated” to find objects displaying this particular ratio. In nature, the fundamental problem for plants is to get as much sunlight as possible. If the leaves are arranged according to a regular pattern, such as “Leaf / quarter-turn / leaf / quarter-turn, …” the leaves will overshadow one another. The challenge is to find an angle of rotation which can be continuously repeated so that no two leaves grow directly above one another (see Figure 6.1). Nature’s solution is using a Fibonacci number sequence (1, 1, 2, 3, 5, 8, 13, 21, …) to calculate the “golden ratio” (5/3, 8/5, 13/8, 21/13, …). -→ Read more in Philosophy for Heroes: Knowledge 

Figure 6.1:Optimal leaf arrangement


If you want to adapt the typography, lib/fonts.tex is the place to look. It consists of:

  • little tweaks for footnotes,
  • line height for lists,
  • space between paragraphs and paragraph indentation,
  • font sizes for captions and the index,
  • font of URLs,
  • background color and font size of listings,
  • typographical tweaks (microtypelmodern),
  • the selection of the font (libertine), and
  • a command that inserts blank pages.

The tweaks are universally recommended, although feel free to select a different font instead of libertine. As the typography is under the control of the specific device when reading the e-book, this applies to only the printable PDF, not the HTML (and thus e-book) output.

The “\sloppy” command is optional; it improves readability by reducing the amount of hyphenation at the cost of possibly more lines of text and more space between the words.

  Chapter Design

The file lib/chapterbox.tex, the chapter box design for the print version, is defined. It replaces the chapter design with a full page with three boxes and the chapter title in huge letters. For the front and back matter, we want the original basic setting with a simple headline with the chapter title and a horizontal line. This can be done by including the file lib/chapterreset.tex before the front matter and before the back matter.

For ease of use, you can use the command

\begin{chapterpage}{Chapter Title}{Chapter Label} …\end{chapterpage}

which is loaded from lib/chapterpage.tex. It sets up the style of the chapter page, as well as the following blank page.

  Header and Footer

In lib/headerfooter.tex, you can edit the style and content of the header and footer. The command


puts the chapter or section title to the inside and the page numbers to the outside of a page. Whether left or right is “inside” depends on whether it is an odd or even page. E-books work on single pages and they have no header, so this command does not affect the style of the e-book output.

The next command, \automark[section]{chapter}, lets the title in the header alternate between the chapter title and section title. If you do not want the section to show up in the header, replace “chapter” with “section.” The third command redefines \headfont that causes the heading to be in small capitals and italics. Finally, the naming of the chapter is redefined, setting it to “Chapter X name of the chapter” without adding a dot after the chapter number.

  TikZ Initialization

TikZ   TikZ is a vector-based drawing language with which you can draw diagrams, charts, tables, fractals, etc.  in high resolution and minimal space.

In lib/inittikz.tex, the TikZ graphics system is loaded. Creating graphics in TikZ goes beyond the scope of this book, but we can help to get you started (see Chapter 3.8). For now we will look only at the initialization.

After loading the basic TikZ packages (and float to add support to force LaTeX to put figures at a certain place), the style of various graphical elements are set up. For example, the text in the nodes of a diagram should have a small font, thick borders, and should be placed a certain distance from other nodes.

By default, tex4ht exports TikZ graphics as vector graphic files (SVG files) and then loads them in the HTML file. Most modern browsers can show vector graphics, but the current e-book converters cannot. They work only with normal images, hence we need to change the behavior of tex4ht.

This is achieved by the code block at the end of the file. It causes all TikZ graphics to be exported into a cache folder, and then to be loaded again from there—as opposed to directly embedded into the PDF as vector graphics.

Long story short, we have to override the tikzpicture command to produce an external PNG file and load that in the HTML file. The PNG files are stored in the tikz-cache/ folder and their resolution can be adapted by changing the density parameter value of the convert command.

Let us look at the details:

  • -extent 1245 This extends the transparent part of the graphic to 1245 pixels. This means all converted TikZ vector graphics will have a width of 1245 pixels.
  • -gravity center If the image is smaller than 1245 pixels, this centers the graphic in the middle of the extended file.
  • -quality 100 Sets maximum compression for TikZ graphics. PNG files are lossless, this increases compile time a little bit, in favor of smaller images.
  • -density 300 Sets the output to 300 dots per inch. This affects the effective size in pixels of the generated graphic.

  Table of Contents

Turning to the next file, lib/tableofcontents.tex, we now arrive at more intricate programming. The first thing you see is that \ifx \HCode \undefined is used instead of \ifxetex. This is because we will be using \HCode to directly insert HTML code into the output. And if HCode is not defined, we will use the normal LaTeX output. But if it is defined, and if our goal is to create HTML files for Amazon, we need to add the ¡nav¿ commands to tell Amazon that what follows now is the table of contents.

For the PDF output, in the case that \HCode is undefined, the command \KOMAoptions{open=…} changes on which side (left or right) the new chapter begins. The template is configured to start chapters on the right side by default (by using the documentclass scrbook—we will discuss this later). For the table of contents, I have decided to let it start on the left (even) page so that the reader can see the full contents of the book in one view. With the following command \KOMAoptions{open=right}, the original setting is restored. Finally, the page needs to be cleared and reset with an empty page style in order to hide the header—we do not want any page numbers in the table of contents section itself.


After finishing my first book, Philosophy for Heroes: Knowledge , I found that it needed additional layers of information to accommodate different types of readers. After considering various options, I decided to add summary (idea) boxes at the end of each section, additional examples, biographies, questions for the reader, and boxes that provide a preview of future books in a series.

Building these boxes is the task of lib/boxes.tex. This file contains a number of graphical elements you can add throughout your book and adapt it to your needs:

\begin{lstlisting}\end{lstlisting} In this environment, everything will be output as you wrote it. This is useful to print out code (like this paragraph) without having to replace all the slashes and braces. The \lstset command determines the formatting of the output, such as break lines at the end of the page, light gray background, indentation, and small font size.

\begin{problem}\end{problem} Creates a box with a question mark icon and the text “Question” on top of it. Use it at the beginning of a section to ask the reader a question that is answered in the following text.

\begin{idea}\end{idea} Creates a box with a light bulb icon and the text “Idea” on top of it. Use it to summarize the previous section and answer the question in the question box.


\begin{example}\end{example} Creates a box with a book and test tube icon and the text “Example” on top of it. Use it for examples that deepen the understanding of the topic in question, but also could be safely skipped.

Biography —Name

\begin{biography}{Name}\end{biography} Creates a box with a book and an identity card as an icon and the text “Biography” on top of it. Some readers want to know more about the people you are discussing in your book, while others want to skip that part. Creating a biography box will accommodate both types of readers. Note the additional parameter (the name of the person), use it like this: \begin{biography}{Alan Watts} Alan Watts was born in …\end{biography}.

Did you know?

\begin{preview}{bibliography id} …\end{preview} Creates a box with an opened book as an icon and the text “Did you know?” on top of it. When referencing your previous books (or giving a preview of your future books), you can use these boxes as an additional advertisement space. It gives the reader an interesting bit to read and might make him or her curious enough to buy or pre-order your next book. Notice the additional parameter (the name of the person), use it like this: \begin{preview}{betterbookswithlatex} In my previous book …\end{preview}. -→ Read more in Better Books with LaTeX

Definition   \begin{definition}{Term}\end{definition} Creates an indented block of text with a black bar to the left (for the PDF output) and the given parameter (the name of the term) in bold and small capitals. This can be used for glossary items to precisely define a concept you have talked about in your text.

Additionally, in lib/quotation.tex, we add support for quotations:

\begin{quotation} …\end{quotation} Creates an intended block of text with a quotation mark graphic in front of it. It signals that there is a quotation from another author. You can use this throughout your book, but I would recommend putting it at the beginning of a section to set the theme or to bring up a certain question.

Finally, we need to display multiple columns in the glossary with lib/multicolbalance.tex.

\begin{multicols}{number of columns}\end{multicols} Splits the text into a number of columns. This is the typical format of the glossary at the end of the book. Books with larger formats might use these throughout the book if necessary. The contents of the columns are balanced (as opposed to filling first the left column and then the right). For readability, the ideal number of columns is two.

  Core Files

Likewise, we already filled the folders mainbackfrontbiographiesexamplesideasquestionsglossary, and images in Chapter 2. We will discuss the remaining files for the HTML conversion in the cssand htlatex folder, as well as the latexmkrc and pgfsys-tex4ht.def files in Chapter 7. Let us now take a look at the core files of a LaTeX project in the root directory. There you can find the language-specific entry files (english.texgerman.tex), and the main project file that binds everything together and provides the structure of the book (main.tex).

As pointed out above in Chapter 6.1.2, in Overleaf , you can select one of the language-specific entry files (english.texgerman.tex) as the main entry file. This way, you can set the language of your project. The parameters american or ngerman of the \usepackage{babel} command reflect this choice. Other than that, the following settings are configured:

  • \documentclass[ …]{scrbook} This sets the document class of your project to a book (two pages and accommodating for the binding). The standard document class is book, using scrbook instead loads a number of additional commands (the KOMA scripts) which we will be using throughout the template. For a detailed documentation of the KOMA script, check out In the template, the pagesize is set to auto, and the bibliography is set to totocnumbered so that it shows up in the table of contents.
  • \title{Title} This sets the title of your LaTeX project. The title will not show up in the final document but is the name of the project listed in Overleaf .
  • \hyphenation{…} Here, you can enter custom hyphenations for fine-tuning. The packages xspace and hyphenat are required for it to work. Not every word is known to LaTeX, and the rules differ between, for example, British and American English. With the hyphenation command, you can enter the hyphenation for special cases yourself. For example, in the Oxford dictionary, “everywhere” is hyphenated as “ev-ery-where” but it might look odd in your text, so you can add \hyphenation{every-where} to tell LaTeX to hyphenate only in the middle. For additional words, simply add them into the bracket: \hyphenation{every-where ti-ger la-tex kit-ten}. You do not need to add a comma or semicolon to separate additional words, just put a space before each new word.

Once the language is set up, the entry file loads lib/packages.tex and then goes into the main file main.tex which is split into five parts:

  • Preamble. For the PDF output, the index is initialized. e-books do not have indexes as they do not have fixed page numbers. Then, the document is started. Everything between \begin{document} and \end{document} is written to the output.
  • Front matter. Front matter pages are numbered with roman numerals (i, ii, iii, iv, …) to set it apart from the main matter. Also, the first few chapters in this part of the book use a basic chapter title formatting (no fancy box). We start with the half title page showing the title, and the title page with the book cover image in case we compile it as a PDF. Then come the publisher, dedication, epigraph, and table of contents page. For the PDF version, we activate the chapterbox formatting to show fancy full-page chapter titles. Next, we show the foreword, and the preface by the author.
  • Main matter. For the main matter, we switch back to a numeric page numbering and insert all the chapter and section files. Here, the bulk of your writing is inserted. This is also the place where you can move around or remove individual sections. For example, if you do not want a page with book advertisements, simply put the comment symbol (%) in front of \input{back/advertisement} and it will no longer appear in the output.
  • Back matter. In the back matter, we show the reader how to proceed from here by advertising our other books and recommending additional books written by other authors to get into the topic more deeply. Next, we insert the author’s biography, as well as the story of how the book was created, giving the interested reader a look behind the curtain. We switch back to the basic chapter design and provide the reader with summaries of the boxes we used (question, idea, and glossary items), as well as a list of sources for the quotations (which we omitted in the text for better readability). Finally, the full bibliography is added in case a reader wants to read in more depth about a certain issue.
  • Appendix. The appendix provides the reader with the index (for the PDF output), a reminder to write a short review online, and farewell words.

Again, you are free to move sections around as you see fit or even disable individual parts by commenting them out (adding a percentage % sign in front of the line). However you decide to design your book, think about what the reader would expect in a certain location of the book. While especially the front and back matter are more or less superfluous parts of a book, they also tell a story and give the reader a context to better understand what you have written in the main part of the book.

This concludes the discussion of the template. In the next sections, we proceed to discuss how to publish the book to specific platforms and polish both the e-book and the print version for release, especially when it comes to graphics.

 LaTeX Help

While we have tested the template together with this book several times, it is likely that you will encounter an issue not discussed here. Creating a document in LaTeX is more complex than in Word, but even in Word there are issues you might run into where the solution is not immediately clear.

If you encounter any error or have a question about LaTeX in the template, please do not hesitate to contact us. The question and the answer might be added to an FAQ for other readers to solve their problems. We offer free support if you provide us with a link to your Overleaf project. For major changes or when more in-depth changes are necessary, one of our LaTeX developers can help you out at an affordable rate. But most issues can probably be solved immediately and for free (“You forgot to close the parentheses,” “You need to load package X,” “Your graphic file is corrupt,” etc.). Simply contact us at and we will see what we can do!

For general LaTeX questions, you can also check out the community at If you post a brief (but working) example of what you are working on, the community can usually provide high-quality advice.

By Clemens Lode

Clemens Lode is a management consultant with focus on agile project management methods (check out He likes to summarize his insights into books, check out his philosophy series "Philosophy for Heroes" here: His core approach to philosophy and management is that people need to be more aware of their limits and ultimately their identity and their vulnerabilities.

Leave a Reply