Login

Template Tag to protect the E-mail address

Author:
end0
Posted:
May 4, 2015
Language:
Python
Version:
1.7
Score:
1 (after 1 ratings)

Update to https://djangosnippets.org/snippets/1907/ to be a bit more flexible, and code cleaned up a tiny bit.

To use, add this snippet as a file in a templatetags folder in an app or in a project. Then include and call the tag with

{% obfuscate_email 'email' %} or {% obfuscate_email 'email' 'link_text' %}

if 'link_text' is provided, it will be used as the text in the body of the <a> tag. If not, then the email will be used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from django import template

register = template.Library()

class ObfuscateEmail(template.Node):
    def __init__(self, email, link_body=None):
        self.email = template.Variable(email)

        try:
            self.link_body = template.Variable(link_body)
        except (template.VariableDoesNotExist, TypeError):
            self.link_body = None

    def render(self, context):
        import random
        email_address = str(self.email)
        character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
        char_list = list(character_set)
        random.shuffle(char_list)

        key = ''.join(char_list)

        cipher_text = ''
        id = 'e' + str(random.randrange(1,999999999))

        for a in email_address:
            cipher_text += key[ character_set.find(a) ]

        script = 'var a="{}";var b=a.split("").sort().join("");var c="{}";var d="";' \
                 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));' \
                 'document.getElementById("{}").innerHTML="<a href=\\"mailto:"+d+"\\">"+{}+"</a>"'.format(key, cipher_text, id, self.link_body or 'd')

        script = "eval(\""+ script.replace("\\","\\\\").replace('"','\\"') + "\")"
        script = '<script type="text/javascript">/*<![CDATA[*/'+script+'/*]]>*/</script>'

        return '<span id="{}">[javascript protected email address]</span>{}'.format(id, script)


@register.tag
def obfuscate_email(parser, token):
    """
        {% obfuscate_email user.email %}
    """

    bits = token.split_contents()
    """
    Pass all of the arguments defined in the template tag except the first one,
    which will be the name of the template tag itself.
    Example: {% do_whatever arg1 arg2 arg3 %}
    *bits[1:] would be: [arg1, arg2, arg3]
    """

    if len(bits) not in (2, 3):
        raise template.TemplateSyntaxError("{} accepts one or two arguments: 1) (required) email 2) (optional) <a> tag body ")

    return ObfuscateEmail(*bits[1:])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.