"Fossies" - the Fresh Open Source Software Archive

Member "calibre-3.45.2/manual/template_lang.rst" (12 Jul 2019, 49177 Bytes) of package /linux/misc/calibre-3.45.2.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format (assuming markdown format). Alternatively you can here view or download the uninterpreted source code file. A member file download can also be achieved by clicking within a package contents listing on the according byte size field.

The calibre template language

The calibre template language is used in various places. It is used to control the folder structure and file name when saving files from the calibre library to the disk or e-book reader. It is also used to define "virtual" columns that contain data from other columns and so on.

The basic template language is very simple, but has very powerful advanced features. The basic idea is that a template consists of text and names in curly brackets that are then replaced by the corresponding metadata from the book being processed. So, for example, the default template used for saving books to device in calibre is:

{author_sort}/{title}/{title} - {authors}

For the book "The Foundation" by "Isaac Asimov" it will become:

Asimov, Isaac/The Foundation/The Foundation - Isaac Asimov

The slashes are text, which is put into the template where it appears. For example, if your template is:

{author_sort} Some Important Text {title}/{title} - {authors}

For the book "The Foundation" by "Isaac Asimov" it will become:

Asimov, Isaac Some Important Text The Foundation/The Foundation - Isaac Asimov

You can use all the various metadata fields available in calibre in a template, including any custom columns you have created yourself. To find out the template name for a column simply hover your mouse over the column header. Names for custom fields (columns you have created yourself) always have a # as the first character. For series type custom fields, there is always an additional field named #seriesname_index that becomes the series index for that series. So if you have a custom series field named #myseries, there will also be a field named #myseries_index.

In addition to the column based fields, you also can use:

{formats} - A list of formats available in the calibre library for a book
{identifiers:select(isbn)} - The ISBN of the book

If a particular book does not have a particular piece of metadata, the field in the template is automatically removed for that book. Consider, for example:

{author_sort}/{series}/{title} {series_index}

If a book has a series, the template will produce:

Asimov, Isaac/Foundation/Second Foundation 3

and if a book does not have a series:

Asimov, Isaac/Second Foundation

(calibre automatically removes multiple slashes and leading or trailing spaces).

Advanced formatting

You can do more than just simple substitution with the templates. You can also conditionally include text and control how the substituted data is formatted.

First, conditionally including text. There are cases where you might want to have text appear in the output only if a field is not empty. A common case is series and series_index, where you want either nothing or the two values with a hyphen between them. calibre handles this case using a special field syntax.

For example, assume you want to use the template:

{series} - {series_index} - {title}

If the book has no series, the answer will be - - title. Many people would rather the result be simply title, without the hyphens. To do this, use the extended syntax {field:|prefix_text|suffix_text}. When you use this syntax, if field has the value SERIES then the result will be prefix_textSERIESsuffix_text. If field has no value, then the result will be the empty string (nothing); the prefix and suffix are ignored. The prefix and suffix can contain blanks. Do not use subtemplates (`{ ... }`) or functions (see below) as the prefix or the suffix.

Using this syntax, we can solve the above series problem with the template:

{series}{series_index:| - | - }{title}

The hyphens will be included only if the book has a series index, which it will have only if it has a series.

Notes: you must include the : character if you want to use a prefix or a suffix. You must either use no | characters or both of them; using one, as in {field:| - }, is not allowed. It is OK not to provide any text for one side or the other, such as in {series:|| - }. Using {title:||} is the same as using {title}.

Second: formatting. Suppose you wanted to ensure that the series_index is always formatted as three digits with leading zeros. This would do the trick:

{series_index:0>3s} - Three digits with leading zeros

If instead of leading zeros you want leading spaces, use:

{series_index:>3s} - Three digits with leading spaces

For trailing zeros, use:

{series_index:0<3s} - Three digits with trailing zeros

If you use series indices with sub values (e.g., 1.1), you might want to ensure that the decimal points line up. For example, you might want the indices 1 and 2.5 to appear as 01.00 and 02.50 so that they will sort correctly. To do this, use:

{series_index:0>5.2f} - Five characters, consisting of two digits with leading zeros, a decimal point, then 2 digits after the decimal point

If you want only the first two letters of the data, use:

{author_sort:.2} - Only the first two letter of the author sort name

The calibre template language comes from Python and for more details on the syntax of these advanced formatting operations, look at the Python documentation.

Advanced features

Using templates in custom columns

There are sometimes cases where you want to display metadata that calibre does not normally display, or to display data in a way different from how calibre normally does. For example, you might want to display the ISBN, a field that calibre does not display. You can use custom columns for this by creating a column with the type 'column built from other columns' (hereafter called composite columns), and entering a template. Result: calibre will display a column showing the result of evaluating that template. To display the ISBN, create the column and enter {identifiers:select(isbn)} into the template box. To display a column containing the values of two series custom columns separated by a comma, use {#series1:||,}{#series2}.

Composite columns can use any template option, including formatting.

You cannot change the data contained in a composite column. If you edit a composite column by double-clicking on any item, you will open the template for editing, not the underlying data. Editing the template on the GUI is a quick way of testing and changing composite columns.

Using functions in templates - single-function mode

Suppose you want to display the value of a field in upper case, when that field is normally in title case. You can do this (and many more things) using the functions available for templates. For example, to display the title in upper case, use {title:uppercase()}. To display it in title case, use {title:titlecase()}.

Function references appear in the format part, going after the : and before the first | or the closing }. If you have both a format and a function reference, the function comes after another :. Functions must always end with (). Some functions take extra values (arguments), and these go inside the ().

Functions are always applied before format specifications. See further down for an example of using both a format and a function, where this order is demonstrated.

The syntax for using functions is {field:function(arguments)}, or {field:function(arguments)|prefix|suffix}. Arguments are separated by commas. Commas inside arguments must be preceded by a backslash ( \ ). The last (or only) argument cannot contain a closing parenthesis ( ) ). Functions return the value of the field used in the template, suitably modified.

Important: If you have programming experience, please note that the syntax in this mode (single function) is not what you might expect. Strings are not quoted. Spaces are significant. All arguments must be constants; there is no sub-evaluation. Do not use subtemplates (`{ ... }`) as function arguments. Instead, use template program mode <template_mode> and general program mode <general_mode>.

Many functions use regular expressions. In all cases, regular expression matching is case-insensitive.

The functions available are listed below. Note that the definitive documentation for functions is available in the section Function classification <template_functions_reference>:

Now, what about using functions and formatting in the same field. Suppose you have an integer custom column called #myint that you want to see with leading zeros, as in 003. To do this, you would use a format of 0>3s. However, by default, if a number (integer or float) equals zero then the field produces the empty value, so zero values will produce nothing, not 000. If you really want to see 000 values, then you use both the format string and the ifempty function to change the empty value back to a zero. The field reference would be:

{#myint:0>3s:ifempty(0)}

Note that you can use the prefix and suffix as well. If you want the number to appear as [003] or [000], then use the field:

{#myint:0>3s:ifempty(0)|[|]}

Using functions in templates - template program mode

The template language program mode differs from single-function mode in that it permits you to write template expressions that refer to other metadata fields, modify values, and do arithmetic. It is a reasonably complete programming language.

You can use the functions documented above in template program mode. See below for details.

Beginning with an example, assume that you want your template to show the series for a book if it has one, otherwise show the value of a custom field #genre. You cannot do this in the basic language because you cannot make reference to another metadata field within a template expression. In program mode, you can. The following expression works:

{#series:'ifempty($, field('#genre'))'}

The example shows several things:

The language is similar to functional languages in that it is built almost entirely from functions. A statement is a function. An expression is a function. Constants and identifiers can be thought of as functions returning the value indicated by the constant or stored in the identifier.

The syntax of the language is shown by the following grammar:

constant   ::= " string " | ' string ' | number
identifier ::= sequence of letters or ``_`` characters
function   ::= identifier ( statement [ , statement ]* )
expression ::= identifier | constant | function | assignment
assignment ::= identifier '=' expression
statement  ::= expression [ ; expression ]*
program    ::= statement

Comments are lines with a '#' character at the beginning of the line.

An expression always has a value, either the value of the constant, the value contained in the identifier, or the value returned by a function. The value of a statement is the value of the last expression in the sequence of statements. As such, the value of the program (statement):

1; 2; 'foobar'; 3

is 3.

Another example of a complex but rather silly program might help make things clearer:

{series_index:'
    substr(
        strcat($, '->',
            cmp(divide($, 2), 1,
                assign(c, 1); substr('lt123', c, 0),
                'eq', 'gt')),
        0, 6)
   '| prefix | suffix}

This program does the following:

For various values of series_index, the program returns:

All the functions listed under single-function mode can be used in program mode. To do so, you must supply the value that the function is to act upon as the first parameter, in addition to the parameters documented above. For example, in program mode the parameters of the test function are test(x, text_if_not_empty, text_if_empty). The x parameter, which is the value to be tested, will almost always be a variable or a function call, often field().

The following functions are available in addition to those described in single-function mode. Remember from the example above that the single-function mode functions require an additional first parameter specifying the field to operate on. With the exception of the id parameter of assign, all parameters can be statements (sequences of expressions). Note that the definitive documentation for functions is available in the section Function classification <template_functions_reference>:

Function classification

generated/en/template_ref

Using general program mode

For more complicated template programs, it is sometimes easier to avoid template syntax (all the { and } characters), instead writing a more classical-looking program. You can do this in calibre by beginning the template with program:. In this case, no template processing is done. The special variable $ is not set. It is up to your program to produce the correct results.

One advantage of program: mode is that the brackets are no longer special. For example, it is not necessary to use [[ and ]] when using the template() function. Another advantage is that program mode templates are compiled to Python and can run much faster than templates in the other two modes. Speed improvement depends on the complexity of the templates; the more complicated the template the more the improvement. Compilation is turned off or on using the tweak compile_gpm_templates (Compile General Program Mode templates to Python). The main reason to turn off compilation is if a compiled template does not work, in which case please file a bug report.

The following example is a program: mode implementation of a recipe on the MobileRead forum: "Put series into the title, using either initials or a shortened form. Strip leading articles from the series name (any)." For example, for the book The Two Towers in the Lord of the Rings series, the recipe gives LotR [02] The Two Towers. Using standard templates, the recipe requires three custom columns and a plugboard, as explained in the following:

The solution requires creating three composite columns. The first column is used to remove the leading articles. The second is used to compute the 'shorten' form. The third is to compute the 'initials' form. Once you have these columns, the plugboard selects between them. You can hide any or all of the three columns on the library view:

First column:
Name: #stripped_series.
Template: {series:re(^(A|The|An)\s+,)||}

Second column (the shortened form):
Name: #shortened.
Template: {#stripped_series:shorten(4,-,4)}

Third column (the initials form):
Name: #initials.
Template: {#stripped_series:re(([^\s])[^\s]+(\s|$),\1)}

Plugboard expression:
Template:{#stripped_series:lookup(.\s,#initials,.,#shortened,series)}{series_index:0>2.0f| [|] }{title}
Destination field: title

This set of fields and plugboard produces:
Series: The Lord of the Rings
Series index: 2
Title: The Two Towers
Output: LotR [02] The Two Towers

Series: Dahak
Series index: 1
Title: Mutineers Moon
Output: Dahak [01] Mutineers Moon

Series: Berserkers
Series Index: 4
Title: Berserker Throne
Output: Bers-kers [04] Berserker Throne

Series: Meg Langslow Mysteries
Series Index: 3
Title: Revenge of the Wrought-Iron Flamingos
Output: MLM [03] Revenge of the Wrought-Iron Flamingos

The following program produces the same results as the original recipe, using only one custom column to hold the results of a program that computes the special title value:

Custom column:
Name: #special_title
Template: (the following with all leading spaces removed)
    program:
    #   compute the equivalent of the composite fields and store them in local variables
        stripped = re(field('series'), '^(A|The|An)\s+', '');
        shortened = shorten(stripped, 4, '-' ,4);
        initials = re(stripped, '[^\w]*(\w?)[^\s]+(\s|$)', '\1');

    #   Format the series index. Ends up as empty if there is no series index.
    #   Note that leading and trailing spaces will be removed by the formatter,
    #   so we cannot add them here. We will do that in the strcat below.
    #   Also note that because we are in 'program' mode, we can freely use
    #   curly brackets in strings, something we cannot do in template mode.
        s_index = template('{series_index:0>2.0f}');

    #   print(stripped, shortened, initials, s_index);

    #   Now concatenate all the bits together. The switch picks between
    #   initials and shortened, depending on whether there is a space
    #   in stripped. We then add the brackets around s_index if it is
    #   not empty. Finally, add the title. As this is the last function in
    #   the program, its value will be returned.
        strcat(
            switch( stripped,
                    '.\s', initials,
                    '.', shortened,
                    field('series')),
            test(s_index, strcat(' [', s_index, '] '), ''),
            field('title'));

Plugboard expression:
Template:{#special_title}
Destination field: title

It would be possible to do the above with no custom columns by putting the program into the template box of the plugboard. However, to do so, all comments must be removed because the plugboard text box does not support multi-line editing. It is debatable whether the gain of not having the custom column is worth the vast increase in difficulty caused by the program being one giant line.

User-defined template functions

You can add your own functions to the template processor. Such functions are written in Python, and can be used in any of the three template programming modes. The functions are added by going to Preferences -> Advanced -> Template functions. Instructions are shown in that dialog.

Special notes for save/send templates

Special processing is applied when a template is used in a save to disk or send to device template. The values of the fields are cleaned, replacing characters that are special to file systems with underscores, including slashes. This means that field text cannot be used to create folders. However, slashes are not changed in prefix or suffix strings, so slashes in these strings will cause folders to be created. Because of this, you can create variable-depth folder structure.

For example, assume we want the folder structure series/series_index - title, with the caveat that if series does not exist, then the title should be in the top folder. The template to do this is:

{series:||/}{series_index:|| - }{title}

The slash and the hyphen appear only if series is not empty.

The lookup function lets us do even fancier processing. For example, assume that if a book has a series, then we want the folder structure series/series index - title.fmt. If the book does not have a series, then we want the folder structure genre/author_sort/title.fmt. If the book has no genre, we want to use 'Unknown'. We want two completely different paths, depending on the value of series.

To accomplish this, we:
  1. Create a composite field (give it lookup name #AA) containing {series}/{series_index} - {title}. If the series is not empty, then this template will produce series/series_index - title.
  2. Create a composite field (give it lookup name #BB) containing {#genre:ifempty(Unknown)}/{author_sort}/{title}. This template produces genre/author_sort/title, where an empty genre is replaced with Unknown.
  3. Set the save template to {series:lookup(.,#AA,#BB)}. This template chooses composite field #AA if series is not empty, and composite field #BB if series is empty. We therefore have two completely different save paths, depending on whether or not series is empty.

Templates and plugboards

Plugboards are used for changing the metadata written into books during send-to-device and save-to-disk operations. A plugboard permits you to specify a template to provide the data to write into the book's metadata. You can use plugboards to modify the following fields: authors, author_sort, language, publisher, tags, title, title_sort. This feature helps people who want to use different metadata in books on devices to solve sorting or display issues.

When you create a plugboard, you specify the format and device for which the plugboard is to be used. A special device is provided, save_to_disk, that is used when saving formats (as opposed to sending them to a device). Once you have chosen the format and device, you choose the metadata fields to change, providing templates to supply the new values. These templates are connected to their destination fields, hence the name plugboards. You can, of course, use composite columns in these templates.

When a plugboard might apply (Content server, save to disk, or send to device), calibre searches the defined plugboards to choose the correct one for the given format and device. For example, to find the appropriate plugboard for an EPUB book being sent to an ANDROID device, calibre searches the plugboards using the following search order:

The tags and authors fields have special treatment, because both of these fields can hold more than one item. A book can have many tags and many authors. When you specify that one of these two fields is to be changed, the template's result is examined to see if more than one item is there. For tags, the result is cut apart wherever calibre finds a comma. For example, if the template produces the value Thriller, Horror, then the result will be two tags, Thriller and Horror. There is no way to put a comma in the middle of a tag.

The same thing happens for authors, but using a different character for the cut, a & (ampersand) instead of a comma. For example, if the template produces the value Blogs, Joe&Posts, Susan, then the book will end up with two authors, Blogs, Joe and Posts, Susan. If the template produces the value Blogs, Joe;Posts, Susan, then the book will have one author with a rather strange name.

Plugboards affect the metadata written into the book when it is saved to disk or written to the device. Plugboards do not affect the metadata used by save to disk and send to device to create the file names. Instead, file names are constructed using the templates entered on the appropriate preferences window.

Helpful tips

You might find the following tips useful.