changeset 4100:810921c33a47

tools (common/template): add filter to get media types: Add 2 filters to get main type and subtype of media type. Jinja2 and Nunjucks don't handle slices in the same way (Python way for Jinja2, JS way for Nunjucks), making it difficult to retrieve main type of a media from media type. Thoses filters work in both cases.
author Goffi <goffi@goffi.org>
date Thu, 22 Jun 2023 15:49:06 +0200
parents 11e802089b19
children 4ed8de94c926
files libervia/backend/tools/common/template.py
diffstat 1 files changed, 14 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/backend/tools/common/template.py	Thu Jun 22 15:47:17 2023 +0200
+++ b/libervia/backend/tools/common/template.py	Thu Jun 22 15:49:06 2023 +0200
@@ -482,6 +482,8 @@
         self.env.filters["highlight"] = self.highlight
         self.env.filters["front_url"] = (self._front_url if front_url_filter is None
                                          else front_url_filter)
+        self.env.filters["media_type_main"] = self.media_type_main
+        self.env.filters["media_type_sub"] = self.media_type_sub
         # custom tests
         self.env.tests["in_the_past"] = self._in_the_past
         self.icons_path = os.path.join(host.media_dir, "fonts/fontello/svg")
@@ -924,6 +926,18 @@
         formatter = formatters.HtmlFormatter(**html_fmt_opts)
         return safe(pygments.highlight(code, lexer, formatter))
 
+    def media_type_main(self, value: Optional[str]) -> Optional[str]:
+        """Return main type of a media type"""
+        if not value:
+            return None
+        return value.partition("/")[0]
+
+    def media_type_sub(self, value: Optional[str]) -> Optional[str]:
+        """Return main type of a media type"""
+        if not value:
+            return None
+        return value.partition("/")[1]
+
     ## custom tests ##
 
     def _in_the_past(self, timestamp):