Debian Codegraph @

docs/dev/plugins/other/templates.rst

raw
1 Add Path Format Functions and Fields
2 ====================================
3
4 Beets supports *function calls* in its path format syntax (see
5 :doc:`/reference/pathformat`). Beets includes a few built-in functions, but
6 plugins can register new functions by adding them to the ``template_funcs``
7 dictionary.
8
9 Here's an example:
10
11 .. code-block:: python
12
13 class MyPlugin(BeetsPlugin):
14 def __init__(self):
15 super().__init__()
16 self.template_funcs["initial"] = _tmpl_initial
17
18
19 def _tmpl_initial(text: str) -> str:
20 if text:
21 return text[0].upper()
22 else:
23 return ""
24
25 This plugin provides a function ``%initial`` to path templates where
26 ``%initial{$artist}`` expands to the artist's initial (its capitalized first
27 character).
28
29 Plugins can also add template *fields*, which are computed values referenced as
30 ``$name`` in templates. To add a new field, add a function that takes an
31 ``Item`` object to the ``template_fields`` dictionary on the plugin object.
32 Here's an example that adds a ``$disc_and_track`` field:
33
34 .. code-block:: python
35
36 class MyPlugin(BeetsPlugin):
37 def __init__(self):
38 super().__init__()
39 self.template_fields["disc_and_track"] = _tmpl_disc_and_track
40
41
42 def _tmpl_disc_and_track(item: Item) -> str:
43 """Expand to the disc number and track number if this is a
44 multi-disc release. Otherwise, just expands to the track
45 number.
46 """
47 if item.disctotal > 1:
48 return "%02i.%02i" % (item.disc, item.track)
49 else:
50 return "%02i" % (item.track)
51
52 With this plugin enabled, templates can reference ``$disc_and_track`` as they
53 can any standard metadata field.
54
55 This field works for *item* templates. Similarly, you can register *album*
56 template fields by adding a function accepting an ``Album`` argument to the
57 ``album_template_fields`` dict.