Login

encode_mailto

Author:
santuri
Posted:
May 6, 2007
Language:
Python
Version:
.96
Score:
4 (after 6 ratings)

This is a django filter which will create an html mailto link when you use the syntax:

{{ "[email protected]"|encode_mailto:"Name" }}

Results in:

<a href="mailto:[email protected]">Name</a>

Except everything is encoded as html digits.

The encoding is a string of html hex and decimal entities generated randomly.

If you simply want a string encoding use:

{{ "name"|encode_string }}

This was inspired by John Gruber's Markdown project

 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
import random
from django import template
"""
    Randomized string encoding
    Inspired by John Gruber's Markdown: 
    http://daringfireball.net/projects/markdown/syntax#autolink
"""
register = template.Library()

#@template.stringfilter
def encode_string(value):
    """
    Encode a string into it's equivalent html entity.

    The tag will randomly choose to represent the character as a hex digit or
    decimal digit.
   
    Use {{ obj.name|encode_string }}
    
    {{ "person"|encode_string }} Becomes something like:
    &#112;&#101;&#x72;&#x73;&#x6f;&#110;
    """
    e_string = "" 
    for a in value:
        type = random.randint(0,1)
        if type:
            en = "&#x%x;" % ord(a)
        else:
            en = "&#%d;" % ord(a)
        e_string += en 
    return e_string

register.filter("encode_string", encode_string)

def encode_mailto(value, arg):
    """
    Encode an e-mail address and its corresponding link name to its equivalent
    html entities.

    Use {{ obj.email|encode_mailto:obj.name }}
    
    {{ "[email protected]"|encode_mailto:"j" }} Becomes something like:
    <a href="&#x6d;&#x61;&#x69;&#x6c;&#x74;&#111;&#x3a;&#106;&#x40;&#106;\
    &#46;&#99;&#x6f;&#x6d;">&#x6a;</a>
    """
    address = 'mailto:%s' % value
    address = encode_string(address)
    name = encode_string(arg)
    tag = "<a href=\"%s\">%s</a>" % (address, name)
    return tag

register.filter("encode_mailto", encode_mailto)

More like this

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

Comments

Please login first before commenting.