Added function filter to template system, closes #429
This commit is contained in:
17
tests/template_filter.py
Normal file
17
tests/template_filter.py
Normal file
@@ -0,0 +1,17 @@
|
||||
""" Example of using a custom python function as an osxphotos template filter
|
||||
|
||||
Use in formath:
|
||||
"{template_field|template_filter.py::myfilter}"
|
||||
|
||||
Your filter function will receive a list of strings even if the template renders to a single value.
|
||||
You should expect a list and return a list and be able to handle multi-value templates like {keyword}
|
||||
as well as single-value templates like {original_name}
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
|
||||
def myfilter(values: List[str]) -> List[str]:
|
||||
""" Custom filter to append "foo-" to template value """
|
||||
values = ["foo-" + val for val in values]
|
||||
return values
|
||||
|
||||
@@ -982,3 +982,31 @@ def test_function_bad(photosdb):
|
||||
"{function:tests/template_function.py::foobar}"
|
||||
)
|
||||
|
||||
|
||||
def test_function_filter(photosdb):
|
||||
""" Test {field|function} filter"""
|
||||
photo = photosdb.get_photo(UUID_MULTI_KEYWORDS)
|
||||
|
||||
rendered, _ = photo.render_template(
|
||||
"{photo.original_filename|function:tests/template_filter.py::myfilter}"
|
||||
)
|
||||
assert rendered == [f"foo-{photo.original_filename}"]
|
||||
|
||||
rendered, _ = photo.render_template(
|
||||
"{photo.original_filename|lower|function:tests/template_filter.py::myfilter}"
|
||||
)
|
||||
assert rendered == [f"foo-{photo.original_filename.lower()}"]
|
||||
|
||||
rendered, _ = photo.render_template(
|
||||
"{photo.original_filename|function:tests/template_filter.py::myfilter|lower}"
|
||||
)
|
||||
assert rendered == [f"foo-{photo.original_filename.lower()}"]
|
||||
|
||||
|
||||
def test_function_filter_bad(photosdb):
|
||||
""" Test invalid {field|function} filter"""
|
||||
photo = photosdb.get_photo(UUID_MULTI_KEYWORDS)
|
||||
with pytest.raises(ValueError):
|
||||
rendered, _ = photo.render_template(
|
||||
"{photo.original_filename|function:tests/template_filter.py::foobar}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user