Added function filter to template system, closes #429

This commit is contained in:
Rhet Turnbull
2021-04-18 17:52:14 -07:00
parent 9371db094e
commit dd6d519135
4 changed files with 85 additions and 11 deletions

17
tests/template_filter.py Normal file
View 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

View File

@@ -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}"
)