diff --git a/various/templatetags/mail.py b/various/templatetags/mail.py index fe11d218..972040f6 100644 --- a/various/templatetags/mail.py +++ b/various/templatetags/mail.py @@ -4,7 +4,7 @@ from urllib.request import quote as urlencode register = template.Library() @register.simple_tag -def maillink(text: str, subject=None, body=None, to=[], attrs=None): +def mailurl(*, subject=None, body=None, to=[]): """TODO: Dokumentace""" if isinstance(to, str): to = [to] @@ -24,6 +24,11 @@ def maillink(text: str, subject=None, body=None, to=[], attrs=None): url = parts[0] + '?' + str.join('&', parts[1:]) else: url = parts[0] + return url + +@register.simple_tag +def maillink(text, subject=None, body=None, to=[], attrs=None): + url = mailurl(subject=subject, body=body, to=to) if not attrs: attrs = '' mezera = ' '*bool(attrs) full_link = f'{text}' diff --git a/various/tests.py b/various/tests.py index 7884e618..0abf4e26 100644 --- a/various/tests.py +++ b/various/tests.py @@ -1,6 +1,6 @@ from django.test import TestCase # TODO: Možná vyrobit separátní soubory v tests/… než mít všechny testy v jednom souboru? -from various.templatetags.mail import maillink +from various.templatetags.mail import maillink, mailurl class MailTagsTest(TestCase): """Testuje template tagy ohledně mailů.""" @@ -24,6 +24,16 @@ class MailTagsTest(TestCase): self.assertRaises(ValueError, lambda: maillink('Nemám příjemce')) self.assertRaises(TypeError, lambda: maillink()) # Nemá text, takže to shodí python + def test_mailurl(self): + self.assertEquals(mailurl(to='some@body.test'), r'mailto:some@body.test') + self.assertEquals(mailurl(to=['some@body.test']), r'mailto:some@body.test') + self.assertEquals(mailurl(to=['alice@test.test', 'bob@jinde.test']), r'mailto:alice@test.test,bob@jinde.test') + self.assertEquals( + mailurl(to='some@body.test', body='Tělo', subject='Předmět'), + r'mailto:some@body.test?subject=P%C5%99edm%C4%9Bt&body=T%C4%9Blo', + ) + self.assertRaises(ValueError, lambda: mailurl()) + def test_render_in_template(self): # Pomocná funkce: vykreslí template do stringu # Ref: https://stackoverflow.com/a/1690879 @@ -33,7 +43,7 @@ class MailTagsTest(TestCase): context = Context(context) return Template(template).render(context) - template=( + template = ( r'{% load mail %}' # TODO: Vyzkoušet i víc adresátů. (Nepamatuji si z hlavy syntaxi…) r'{% maillink "Text" to="alice@test.test" subject="Oprava řešení" %}' @@ -42,3 +52,9 @@ class MailTagsTest(TestCase): render_template(template), r'Text', ) + + mailurltemplate = ( + r'{% load mail %}' + r'{% mailurl to="alice@test.test" subject="Čau Alice" %}' + ) + self.assertEquals(render_template(mailurltemplate), r'mailto:alice@test.test?subject=%C4%8Cau%20Alice')