The Basics of Templating

At its simplest, a Mercurial template is a piece of text. Some of the text never changes, while other parts are expanded, or replaced with new text, when necessary.

Before we continue, let’s look again at a simple example of Mercurial’s normal output.

$ hg log -r1
changeset:   1:59ae2fd35d8a
tag:         mytag
user:        Bryan O'Sullivan <bos@serpentine.com>
date:        Tue May 05 06:44:45 2009 +0000
summary:     added line to end of <<hello>> file.

Now, let’s run the same command, but using a template to change its output.

$ hg log -r1 --template 'i saw a changeset\n'
i saw a changeset

The example above illustrates the simplest possible template; it’s just a piece of static text, printed once for each changeset. The --template option to the hg log command tells Mercurial to use the given text as the template when printing each changeset.

Notice that the template string above ends with the text \n. This is an escape sequence, telling Mercurial to print a newline at the end of each template item. If you omit this newline, Mercurial will run each piece of output together. See Escape Sequences for more details.

A template that prints a fixed string of text all the time isn’t very useful; let’s try something a bit more complex.

$ hg log --template 'i saw a changeset: {desc}\n' i saw a changeset: Added tag v0.1 for changeset cefd14841d41 i saw a changeset: Added tag mytag for changeset 59ae2fd35d8a i saw a changeset: added line to end of <<hello>> file. in addition, added a file with the helpful ...

Get Mercurial: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.