Reference for all built-in template language functions

Here, we document all the built-in functions available in the calibre template language. Every function is implemented as a class in python and you can click the source links to see the source code, in case the documentation is insufficient. The functions are arranged in logical groups by type.

Boolean

or(value [, value]*)

class calibre.utils.formatter_functions.BuiltinOr[código fonte]

or(value [, value]*) – devolve a string «1» se algum valor não estiver vazio, caso contrário, devolve a string vazia. Esta função funciona bem com o teste ou first_non_empty. Em muitos casos o operador || pode substituir esta função.

Get values from metadata

annotation_count ()

class calibre.utils.formatter_functions.BuiltinAnnotationCount[código fonte]

annotation_count () - devolve o número total de anotações de todos os tipos anexados ao livro atual. Esta função funciona apenas na IGU.

List lookup

identifier_in_list(val, nome_id [, val_encontrado, val_nao_encontrado])

class calibre.utils.formatter_functions.BuiltinIdentifierInList[código fonte]

identifier_in_list(val, nome_id [, val_encontrado, val_nao_encontrado]) – trata VAL como uma lista de identificadores separados por vírgulas. Um identificador tem o formato «nome_id: valor». O parâmetro nome_id é o texto a ser procurado, pode ser «nome_id» ou «nome_id:regexp». O primeiro caso irá fazer correspondência se houver um qualquer identificador correspondente a nome_id. O segundo caso irá fazer correspondência se nome_id corresponder a um identificador e a expressão regular (regexp) corresponder com o valor do identificador. Se forem indicados val_encontrado e val_nao_encontrado, então se houver correspondência será devolvido val_encontrado, de contrário irá devolver val_nao_encontrado. Se não forem indicados val_encontrado e val_nao_encontrado, então se houver uma correspondência, será devolvido o par identificador:valor, de contrário obterá uma string vazia.

List manipulation

list_equals(list1, sep1, list2, sep2, yes_val, no_val)

class calibre.utils.formatter_functions.BuiltinListEquals[código fonte]

list_equals(list1, sep1, list2, sep2, yes_val, no_val) – devolverá yes_val se list1 e list2 contiverem os mesmos itens, caso contrário devolverá no_val. Os itens são determinados dividindo cada lista usando o carácter separador apropriado (sep1 ou sep2). A ordem dos itens das listas não é relevante. A comparação não diferencia maiúsculas.

range(início, fim, passo, limite) — devolve uma lista de números gerada ao percorrer o intervalo especificado pelos parâmetros “início”, “fim” e “passo”, com um comprimento máximo de “limite”. O primeiro valor produzido é “início”. Os valores subsequentes v_seguinte são v_atual+passo. O loop continua enquanto v_seguinte < “fim”, caso “passo” seja positivo, de contrário v_seguinte > “fim”. Uma lista vazia é produzida caso “início” falhe no teste: “início” >= “fim” caso o “passo” seja positivo. O “limite” define o comprimento máximo da lista e tem um valor predefinido de 1000. O parâmetro “início”, “passo” e “limite” são opcionais. Chamar range() com um argumento especifica o “fim”. Dois argumentos especificam “início” e “fim”. Três argumentos especificam “início”, “fim”, e “passo”. Quatro argumentos especificam “início”, “fim”, “passo” e “limite”. Exemplos: range(5)

class calibre.utils.formatter_functions.BuiltinRange[código fonte]

range(início, fim, passo, limite) — devolve uma lista de números gerada ao percorrer o intervalo especificado pelos parâmetros “início”, “fim” e “passo”, com um comprimento máximo de “limite”. O primeiro valor produzido é “início”. Os valores subsequentes v_seguinte são v_atual+passo. O loop continua enquanto v_seguinte < “fim”, caso “passo” seja positivo, de contrário v_seguinte > “fim”. Uma lista vazia é produzida caso “início” falhe no teste: “início” >= “fim” caso o “passo” seja positivo. O “limite” define o comprimento máximo da lista e tem um valor predefinido de 1000. O parâmetro “início”, “passo” e “limite” são opcionais. Chamar range() com um argumento especifica o “fim”. Dois argumentos especificam “início” e “fim”. Três argumentos especificam “início”, “fim”, e “passo”. Quatro argumentos especificam “início”, “fim”, “passo” e “limite”. Exemplos: range(5)-> “0,1,2,3,4”. range(0,5)-> “0,1,2,3,4”. range(-1,5)-> “-1,0,1,2,3,4”. range(1,5)-> “1,2,3,4”. range(1,5,2)-> “1,3”. range(1,5,2,5)-> “1,3”. range(1,5,2,1)-> erro(limite excedido).

API of the Metadata objects

The python implementation of the template functions is passed in a Metadata object. Knowing it’s API is useful if you want to define your own template functions.

class calibre.ebooks.metadata.book.base.Metadata(title, authors=('Desconhecido',), other=None, template_cache=None, formatter=None)[código fonte]

A class representing all the metadata for a book. The various standard metadata fields are available as attributes of this object. You can also stick arbitrary attributes onto this object.

Metadata from custom columns should be accessed via the get() method, passing in the lookup name for the column, for example: «#mytags».

Use the is_null() method to test if a field is null.

This object also has functions to format fields into strings.

The list of standard metadata fields grows with time is in STANDARD_METADATA_FIELDS.

Please keep the method based API of this class to a minimum. Every method becomes a reserved field name.

is_null(field)[código fonte]

Return True if the value of field is null in this object. “null” means it is unknown or evaluates to False. So a title of _(“Unknown”) is null or a language of “und” is null.

Be careful with numeric fields since this will return True for zero as well as None.

Also returns True if the field does not exist.

deepcopy(class_generator=<function Metadata.<lambda>>)[código fonte]

Do not use this method unless you know what you are doing, if you want to create a simple clone of this object, use deepcopy_metadata() instead. Class_generator must be a function that returns an instance of Metadata or a subclass of it.

get_identifiers()[código fonte]

Return a copy of the identifiers dictionary. The dict is small, and the penalty for using a reference where a copy is needed is large. Also, we don’t want any manipulations of the returned dict to show up in the book.

set_identifiers(identifiers)[código fonte]

Set all identifiers. Note that if you previously set ISBN, calling this method will delete it.

set_identifier(typ, val)[código fonte]

If val is empty, deletes identifier of type typ

standard_field_keys()[código fonte]

return a list of all possible keys, even if this book doesn’t have them

custom_field_keys()[código fonte]

return a list of the custom fields in this book

all_field_keys()[código fonte]

All field keys known by this instance, even if their value is None

metadata_for_field(key)[código fonte]

return metadata describing a standard or custom field.

all_non_none_fields()[código fonte]

Return a dictionary containing all non-None metadata fields, including the custom ones.

get_standard_metadata(field, make_copy)[código fonte]

return field metadata from the field if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

get_all_standard_metadata(make_copy)[código fonte]

return a dict containing all the standard field metadata associated with the book.

get_all_user_metadata(make_copy)[código fonte]

return a dict containing all the custom field metadata associated with the book.

get_user_metadata(field, make_copy)[código fonte]

return field metadata from the object if it is there. Otherwise return None. field is the key name, not the label. Return a copy if requested, just in case the user wants to change values in the dict.

set_all_user_metadata(metadata)[código fonte]

store custom field metadata into the object. Field is the key name not the label

set_user_metadata(field, metadata)[código fonte]

store custom field metadata for one column into the object. Field is the key name not the label

remove_stale_user_metadata(other_mi)[código fonte]

Remove user metadata keys (custom column keys) if they don’t exist in “other_mi”, which must be a metadata object

template_to_attribute(other, ops)[código fonte]

Takes a list [(src,dest), (src,dest)], evaluates the template in the context of other, then copies the result to self[dest]. This is on a best-efforts basis. Some assignments can make no sense.

smart_update(other, replace_metadata=False)[código fonte]

Merge the information in other into self. In case of conflicts, the information in other takes precedence, unless the information in other is NULL.

format_field(key, series_with_index=True)[código fonte]

Returns the tuple (display_name, formatted_value)

to_html()[código fonte]

A HTML representation of this object.

calibre.ebooks.metadata.book.base.STANDARD_METADATA_FIELDS

The set of standard metadata fields.


'''
All fields must have a NULL value represented as None for simple types,
an empty list/dictionary for complex types and (None, None) for cover_data
'''

SOCIAL_METADATA_FIELDS = frozenset((
    'tags',             # Ordered list
    'rating',           # A floating point number between 0 and 10
    'comments',         # A simple HTML enabled string
    'series',           # A simple string
    'series_index',     # A floating point number
    # Of the form { scheme1:value1, scheme2:value2}
    # For example: {'isbn':'123456789', 'doi':'xxxx', ... }
    'identifiers',
))

'''
The list of names that convert to identifiers when in get and set.
'''

TOP_LEVEL_IDENTIFIERS = frozenset((
    'isbn',
))

PUBLICATION_METADATA_FIELDS = frozenset((
    'title',            # title must never be None. Should be _('Unknown')
    # Pseudo field that can be set, but if not set is auto generated
    # from title and languages
    'title_sort',
    'authors',          # Ordered list. Must never be None, can be [_('Unknown')]
    'author_sort_map',  # Map of sort strings for each author
    # Pseudo field that can be set, but if not set is auto generated
    # from authors and languages
    'author_sort',
    'book_producer',
    'timestamp',        # Dates and times must be timezone aware
    'pubdate',
    'last_modified',
    'rights',
    # So far only known publication type is periodical:calibre
    # If None, means book
    'publication_type',
    'uuid',             # A UUID usually of type 4
    'languages',        # ordered list of languages in this publication
    'publisher',        # Simple string, no special semantics
    # Absolute path to image file encoded in filesystem_encoding
    'cover',
    # Of the form (format, data) where format is, e.g. 'jpeg', 'png', 'gif'...
    'cover_data',
    # Either thumbnail data, or an object with the attribute
    # image_path which is the path to an image file, encoded
    # in filesystem_encoding
    'thumbnail',
))

BOOK_STRUCTURE_FIELDS = frozenset((
    # These are used by code, Null values are None.
    'toc', 'spine', 'guide', 'manifest',
))

USER_METADATA_FIELDS = frozenset((
    # A dict of dicts similar to field_metadata. Each field description dict
    # also contains a value field with the key #value#.
    'user_metadata',
))

DEVICE_METADATA_FIELDS = frozenset((
    'device_collections',   # Ordered list of strings
    'lpath',                # Unicode, / separated
    'size',                 # In bytes
    'mime',                 # Mimetype of the book file being represented
))

CALIBRE_METADATA_FIELDS = frozenset((
    'application_id',   # An application id, currently set to the db_id.
    'db_id',            # the calibre primary key of the item.
    'formats',          # list of formats (extensions) for this book
    # a dict of user category names, where the value is a list of item names
    # from the book that are in that category
    'user_categories',
    # a dict of items to associated hyperlink
    'link_maps',
))

ALL_METADATA_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           USER_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# All fields except custom fields
STANDARD_METADATA_FIELDS = SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS)

# Metadata fields that smart update must do special processing to copy.
SC_FIELDS_NOT_COPIED =     frozenset(('title', 'title_sort', 'authors',
                                      'author_sort', 'author_sort_map',
                                      'cover_data', 'tags', 'languages',
                                      'identifiers'))

# Metadata fields that smart update should copy only if the source is not None
SC_FIELDS_COPY_NOT_NULL =  frozenset(('device_collections', 'lpath', 'size', 'comments', 'thumbnail'))

# Metadata fields that smart update should copy without special handling
SC_COPYABLE_FIELDS =       SOCIAL_METADATA_FIELDS.union(
                           PUBLICATION_METADATA_FIELDS).union(
                           BOOK_STRUCTURE_FIELDS).union(
                           DEVICE_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS) - \
                           SC_FIELDS_NOT_COPIED.union(
                           SC_FIELDS_COPY_NOT_NULL)

SERIALIZABLE_FIELDS =      SOCIAL_METADATA_FIELDS.union(
                           USER_METADATA_FIELDS).union(
                           PUBLICATION_METADATA_FIELDS).union(
                           CALIBRE_METADATA_FIELDS).union(
                           DEVICE_METADATA_FIELDS) - \
                           frozenset(('device_collections', 'formats',
                               'cover_data'))
# these are rebuilt when needed