mirror of
https://codeberg.org/Mo8it/AdvLabDB.git
synced 2024-12-30 17:33:51 +00:00
Add link formatters bases
This commit is contained in:
parent
305609396f
commit
5e59f0fe72
1 changed files with 43 additions and 2 deletions
|
@ -1,7 +1,7 @@
|
|||
# Functions not dependent on advlabdb
|
||||
|
||||
from flask import flash
|
||||
from markupsafe import Markup
|
||||
from flask import flash, url_for
|
||||
from markupsafe import Markup, escape
|
||||
|
||||
|
||||
def flashRandomPassword(email: str, password: str):
|
||||
|
@ -49,3 +49,44 @@ def str_formatter(view, context, model, name):
|
|||
return attr.str()
|
||||
|
||||
return attr
|
||||
|
||||
|
||||
def _details_link(url, attr, attr_formatter):
|
||||
return f"<a href='{url}?id={attr.id}'>{escape(attr_formatter(attr))}</a>"
|
||||
|
||||
|
||||
def _default_attr_formatter(attr):
|
||||
return attr
|
||||
|
||||
|
||||
def link_formatter(model, name, endpoint, attr_formatter=_default_attr_formatter):
|
||||
attr = deep_getattr(model, name)
|
||||
|
||||
if attr is None:
|
||||
return ""
|
||||
|
||||
url = url_for(f"{endpoint}.details_view")
|
||||
|
||||
if hasattr(attr, "__iter__") and not isinstance(attr, str):
|
||||
# List of attributes
|
||||
links = (_details_link(url, a, attr_formatter) for a in attr)
|
||||
return Markup(", ".join(links))
|
||||
|
||||
# Single attribute
|
||||
return Markup(_details_link(url, attr, attr_formatter))
|
||||
|
||||
|
||||
def link_formatter_factory(endpoint, attr_formatter=_default_attr_formatter):
|
||||
def formatter(view, context, model, name):
|
||||
return link_formatter(model, name, endpoint, attr_formatter)
|
||||
|
||||
return formatter
|
||||
|
||||
|
||||
def email_formatter(view, context, model, name):
|
||||
attr = deep_getattr(model, name)
|
||||
|
||||
if attr is None:
|
||||
return ""
|
||||
|
||||
return Markup(f"<a href='mailto:{escape(attr)}'>{escape(attr)}</a>")
|
||||
|
|
Loading…
Reference in a new issue