From 173519a630620d2839d12f127b3363a18e132b67 Mon Sep 17 00:00:00 2001 From: Goffi Date: Thu, 22 Jun 2023 15:49:06 +0200 Subject: [PATCH] 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. --- libervia/backend/tools/common/template.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/libervia/backend/tools/common/template.py b/libervia/backend/tools/common/template.py index a71a236e..f0bd11a0 100644 --- a/libervia/backend/tools/common/template.py +++ b/libervia/backend/tools/common/template.py @@ -482,6 +482,8 @@ class Renderer(object): 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 @@ class Renderer(object): 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):