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.
Arithmetic¶
add(x [, y]*)¶
ceiling(x)¶
divide(x, y)¶
floor(x)¶
fractional_part(x)¶
multiply(x [, y]*)¶
round(x)¶
subtract(x, y)¶
Boolean¶
and(value[, value]*)¶
not(value)¶
or(value [, value]*)¶
Date functions¶
date_arithmetic(date, calc_spec, fmt)¶
- class calibre.utils.formatter_functions.BuiltinDateArithmetic[源代码]¶
date_arithmetic(date, calc_spec, fmt) –使用“calc_spec”从“date”计算新日期。返回根据可选“fmt”格式化的新日期:如果未提供,则结果将为iso格式。calc_spec是通过串联成对的“vW”(valueWhat)形成的字符串,其中“v”可能是负数,W是以下字母之一: s: 将“v”秒添加到“date”,m: 将“v”分钟添加到“date”,h: 将“v”小时添加到“date”,d: 将“v”天添加到“date”,w: 将“v”周添加到“date”,y: 将“v”年添加到“date”,其中一年是365天。 示例:“1s3d-1m”将增加1秒,增加3天,并从“date”中减去1分钟。
days_between(date1, date2)¶
today()¶
Formatting values¶
finish_formatting(val, fmt, prefix, suffix)¶
format_date(val, format_string)¶
- class calibre.utils.formatter_functions.BuiltinFormatDate[源代码]¶
format_date(val, format_string) – 使用format_string格式化该值(必须为日期),并返回一个字符串。 格式代码为: d:以带前导零(1到31)的数字表示的天 dd:以带前导零(01到31)的数字表示的天 ddd:本地化的缩写日名(例如,“ 周一”到“ 周日” ”)。 dddd:本地化的长名称(例如,“星期一”至“星期日”)。 M:月份,不带前导零(1到12)的数字。 MM:月份的数字,前导零(01到12) MMM:本地化月份的缩写名称(例如,“1月”到“ 12月”)。 MMMM:本地化的长月份名称(例如,“ 一月”到“ 十二月”)。 yy:年份为两位数字(00至99)。 yyyy:年份为四位数。 h:无前导0的小时(0至11或0至23,取决于am / pm) hh:无前导0的小时(00至11或00至23,取决于am / pm) m:分钟无前导0(0到59) mm:无前导0(00到59)的分钟 s:无前导0(0到59)的秒 ss:有前导0(00到59)的秒 ap:使用12个小时的时钟代替24个小时的时钟,用“ ap”替换为am或pm AP的本地化字符串:使用12个小时的时钟而不是24小时时钟,用“ AP”替换为AM或PM iso:带时间和时区的日期。 to_number必须是唯一的格式:日期为浮点数 from_number[:fmt]:如果存在,则使用fmt格式化时间戳,否则为iso
format_date_field(field_name, format_string)¶
format_number(v, template)¶
human_readable(v)¶
rating_to_stars(value, use_half_stars)¶
Get values from metadata¶
annotation_count()¶
approximate_formats()¶
- class calibre.utils.formatter_functions.BuiltinApproximateFormats[源代码]¶
approximate_formats() – 返回一个逗号分隔的格式列表,其中一个点与书籍关联。不能保证这个列表是正确的,尽管它可能是正确的。这个函数可以在模板程序模式下调用,使用模板 “{:’approximate_formats()’}”。请注意,如在EPUB中格式名称总是大写的。这个函数只在图形界面中工作。如果要在保存到硬盘或发送到设备模板中使用这些值,则要自定义一个“基于其它栏目创建栏目”,使用该栏目的模板中的函数,并在保存/发送模板中使用该栏目的值
booksize()¶
connected_device_name(storage_location)¶
connected_device_uuid(storage_location)¶
current_library_name()¶
current_library_path()¶
current_virtual_library_name()¶
field(lookup_name)¶
formats_modtimes(date_format)¶
formats_paths()¶
formats_sizes()¶
has_cover()¶
is_marked()¶
language_codes(lang_strings)¶
language_strings(lang_codes, localize)¶
ondevice()¶
raw_field(lookup_name [, optional_default])¶
raw_list(lookup_name, separator)¶
series_sort()¶
user_categories()¶
virtual_libraries()¶
If-then-else¶
contains(val, pattern, text if match, text if not match)¶
field_exists(field_name)¶
ifempty(val, text if empty)¶
test(val, text if not empty, text if empty)¶
Iterating over values¶
first_non_empty(value[, value]*)¶
lookup(val, [pattern, field,]+ else_field)¶
switch(val, [pattern, value,]+ else_value)¶
switch_if([test_expression, value_expression,]+ else_expression)¶
- class calibre.utils.formatter_functions.BuiltinSwitchIf[源代码]¶
switch_if([test_expression, value_expression,]+ else_expression) – 对于每个“test_expression,value_expression”对,检查test_express是否为True(非空),如果为True,则返回value_express的结果。如果没有test_expression为True,则返回else_expression的结果。您可以有任意数量的“test_expression,value_expression”对。
List lookup¶
identifier_in_list(val, id_name [,found_val, not_found_val])¶
- class calibre.utils.formatter_functions.BuiltinIdentifierInList[源代码]¶
identifier_in_list(val, id_name [,found_val, not_found_val]) – 将 val 视为以逗号分隔的标识符列表。 标识符的格式为“id_name:value”。 id_name 参数是要搜索的 id_name 文本,可以是“id_name”或“id_name:regexp”。 如果有任何标识符与 id_name 匹配,则第一种情况匹配。 如果 id_name 与标识符匹配并且正则表达式与标识符的值匹配,则第二种情况匹配。 如果提供了found_val和not_found_val,则如果存在匹配则返回found_val,否则返回not_found_val。 如果未提供found_val和not_found_val,则如果存在匹配则返回identifier:value对,否则返回空字符串。
in_list(val, separator, [ pattern, found_val, ]+ not_found_val)¶
list_item(val, index, separator)¶
select(val, key)¶
str_in_list(val, separator, [string, found_val, ]+ not_found_val)¶
List manipulation¶
count(val, separator)¶
list_count_matching(list, pattern, separator)¶
list_difference(list1, list2, separator)¶
list_equals(list1, sep1, list2, sep2, yes_val, no_val)¶
list_intersection(list1, list2, separator)¶
list_join(with_separator, list1, separator1 [, list2, separator2]*)¶
- class calibre.utils.formatter_functions.BuiltinListJoin[源代码]¶
list_join(with_separator, list1, separator1 [, list2, separator2]*) –返回通过使用with_separaator连接源列表lists (list1, 等) 中的结果列表中的项而生成的列表。 每个源列表list[123…] 中的项目由关联的分隔符separator[123…]分隔。 列表可以不包含值。 它可以是一个类似于出版商这样的单一值的字段,实际上是一个单项列表。 使用不区分大小写的比较来删除重复项。 项目将按照它们在源列表中出现的顺序返回。 如果列表中的项目仅字母大小写不同,则使用最后一个。 所有分隔符可以是多个字符。 例子:
- program:
list_join(‘#@#’, $authors, ‘&’, $tags, ‘,’)
- 您可以对先前调用list_join的结果使用list_join,如下所示:
program:
a = list_join(‘#@#’, $authors, ‘&’, $tags, ‘,’); b = list_join(‘#@#’, a, ‘#@#’, $#genre, ‘,’, $#people, ‘&’)
- 可以使用表达式生成列表。例如,假设您想要作者和#genre(类型)的项目,但将genre改为单词“Genre:”,后跟该类型的第一个字母,即,类型“Fiction”变为“Genre: F”。以下操作将实现这一点:
- program:
list_join(‘#@#’, $authors, ‘&’, list_re($#genre, ‘,’, ‘^(.).*$’, ‘Genre: 1’), ‘,’)
list_re(src_list, separator, include_re, opt_replace)¶
list_re_group(src_list, separator, include_re, search_re[, group_1_template]+)¶
list_remove_duplicates(list, separator)¶
list_sort(list, direction, separator)¶
list_union(list1, list2, separator)¶
range(start, stop, step, limit)¶
- class calibre.utils.formatter_functions.BuiltinRange[源代码]¶
range(start, stop, step, limit) –返回通过在参数start、stop和step指定的范围内循环生成的数字列表,最大长度为limit。 产生的第一个值是“start”。 后续值next_v为current_v+step。step为正。当next_v<stop时,则循环继续,否则当next_v>stop时停止。 生成一个空列表,如果启动未通过测试:start>=stop 。此时step为正。 limit设置列表的最大长度,默认值为1000。参数start、step和limit是可选的。 调用 range() 同时带有一个指定参数stop或两个指定参数start和stop或三个指定参数start、stop和step或四个指定参数start、stop、step和limit。 示例: 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) -> error(limit exceeded).
subitems(val, start_index, end_index)¶
- class calibre.utils.formatter_functions.BuiltinSubitems[源代码]¶
subitems(val, start_index, end_index) – 此函数用于拆分诸如题材等类型的项目列表。它将该值解释为逗号分隔的项列表,其中每个项都是句点分隔的列表。返回一个新列表,该列表首先找到所有用句点分隔的项目,然后将每个这样的项目从start_index提取到end_index组件,然后将结果一起返回。句点分隔列表中的第一个组件的索引为零。如果索引为负数,则从列表末尾开始计数。作为一种特殊情况,假定end_index为零是列表的长度。 使用基本模板模式并假定#genre值为“ A.B.C”的示例: {#genre:subitems(0,1)} 返回结果 “A”。 {#genre:subitems(0,2)} 返回结果 “A.B”。{#genre:subitems(1,0)} 返回结果 “B.C”。假设#genre值为”A.B.C, D.E.F”, {#genre:subitems(0,1)}返回“A,D”。{#genre:subitems(0,2)}返回“A.B,D.E”
sublist(val, start_index, end_index, separator)¶
- class calibre.utils.formatter_functions.BuiltinSublist[源代码]¶
sublist(val, start_index, end_index, separator) –将该值解释为以`分隔符`分隔的项目列表,将从`start_index`生成的新列表返回给`end_index`项目。第一个项目是零号。如果索引为负数,则从列表末尾开始计数。作为一种特殊情况,假定end_index为零是列表的长度。 示例: 使用基本模板模式,并假定标签栏目(用逗号分隔)包含“ A,B,C”,{tags:sublist(0,1,\,)}返回“ A”。 {tags:sublist(0,1,\,)}返回“ C”。
{tags:sublist(-1,0,\,)} 返回“ A,B”。
Other¶
arguments(id[=expression] [, id[=expression]]*)¶
assign(id, val)¶
globals(id[=expression] [, id[=expression]]*)¶
print(a[, b]*)¶
Recursion¶
eval(template)¶
template(x)¶
Relational¶
first_matching_cmp(val, [cmp1, result1,]+, else_result)¶
- class calibre.utils.formatter_functions.BuiltinFirstMatchingCmp[源代码]¶
first_matching_cmp(val, [cmp1, result1,]+, else_result) – 依次比较“ val <cmpN”,如第一次比较满足(即val小于cmpN)则返回“resultN”。 如果没有一次比较满足,则返回else_result。 示例: first_matching_cmp(10,5,”small”,10,”middle”,15,”large”,”giant”) 返回”large”。 相同例子中如果第一个值为16,则返回”giant”。
strcmp(x, y, lt, eq, gt)¶
strcmpcase(x, y, lt, eq, gt)¶
String case changes¶
capitalize(val)¶
lowercase(val)¶
titlecase(val)¶
uppercase(val)¶
String manipulation¶
character(character_name)¶
re(val, pattern, replacement)¶
re_group(val, pattern [, template_for_group]*)¶
- class calibre.utils.formatter_functions.BuiltinReGroup[源代码]¶
re_group(val, pattern [, template_for_group]*) – 返回一个字符串,该字符串是通过将正则表达式应用于val,并将每个匹配的实例替换为通过将每个匹配的组替换为相应模板返回的值计算的字符串而生成的字符串。 该组的原始匹配值可用$表示。 在模板程序模式下,与模板和eval函数一样,您可以使用[[ for { and ]] for }.下面的示例表示在模板程序模式下查找具有多个单词的序列,并将第一个单词大写: {series:’re_group($, “(S* )(.*)”, “[[$:uppercase()]]”, “[[$]]”)’}
shorten(val, left chars, middle text, right chars)¶
- class calibre.utils.formatter_functions.BuiltinShorten[源代码]¶
shorten(val, left chars, middle text, right chars) – 返回val的缩写版本,由val开头的“左字符”字符组成,后跟“中间文本”,然后是字符串末尾的“右字符”字符。左字符`和`右字符`必须是整数。例如,假设书名为”Ancient English Laws in the Times of Ivanhoe”,您希望它最多只能容纳15个字符。如果使用{title:Shorten(9,-,5)},则结果为`Ancient E-nhoe。如果该字段的长度小于左字符+右字符+`中间文本`的长度,则该字段将被原封不动地使用。例如,标题‘The Dome`不会改变。
strcat(a [, b]*)¶
strcat_max(max, string1 [, prefix2, string2]*)¶
strlen(a)¶
substr(str, start, end)¶
swap_around_articles(val, separator)¶
swap_around_comma(val)¶
to_hex(val)¶
transliterate(a)¶
Template database functions¶
book_values(column, query, sep, use_vl)¶
extra_file_modtime(file_name, format_spec)¶
extra_file_names(sep [, pattern])¶
extra_file_size(file_name)¶
get_link(field_name, field_value)¶
get_note(field_name, field_value, plain_text)¶
has_extra_files([pattern])¶
has_note(field_name, field_value)¶
other¶
set_globals(id[=expression] [, id[=expression]]*)¶
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=('未知',), other=None, template_cache=None, formatter=None)[源代码]¶
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)[源代码]¶
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>>)[源代码]¶
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()[源代码]¶
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)[源代码]¶
Set all identifiers. Note that if you previously set ISBN, calling this method will delete it.
- all_non_none_fields()[源代码]¶
Return a dictionary containing all non-None metadata fields, including the custom ones.
- get_standard_metadata(field, make_copy)[源代码]¶
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)[源代码]¶
return a dict containing all the standard field metadata associated with the book.
- get_all_user_metadata(make_copy)[源代码]¶
return a dict containing all the custom field metadata associated with the book.
- get_user_metadata(field, make_copy)[源代码]¶
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)[源代码]¶
store custom field metadata into the object. Field is the key name not the label
- set_user_metadata(field, metadata)[源代码]¶
store custom field metadata for one column into the object. Field is the key name not the label
- remove_stale_user_metadata(other_mi)[源代码]¶
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)[源代码]¶
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.
- 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