Login

{% exec %} template tag

Author:
aquila
Posted:
March 30, 2007
Language:
Python
Version:
.96
Score:
-6 (after 12 ratings)

usage: 1、 {% exec %} class A: def call(self): print "I Love Python!"; {% endexec %}

2、 {% exec from django.conf import settings; %}

3、 {% exec %} try: html = '' if book: html = book.TransToHtml().encode('utf8'); except Exception,msg: html = str(msg);

if settings.TEMPLATE_DEBUG: open('c:/index.html','wb').write(html);

{% endexec %}

 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Author: aquila ([email protected])

"""
    Execute any python code.

    Example:
usage:
1.
{% exec %}
class A:
    def __call__(self):
        print "I Love Python!";
{% endexec %}

2.
{% exec from django.conf import settings; %}

3.
{% exec %}
try:
	html = ''
	if book:
		html = book.TransToHtml().encode('utf8');
except Exception,msg:
	html = str(msg);
	
if settings.TEMPLATE_DEBUG:	
	open('c:/index.html','wb').write(html);
	
{% endexec %}

"""
from django import template

register = template.Library()

class ExecNode(template.Node):
    def __init__(self, arg, nodelist=None):
        self._arg, self._nodelist = arg, nodelist;
    
    def render(self, context):
        clist = list(context);
        clist.reverse();

        env = {}
        for c in clist:
            env.update(c)
        
        if self._nodelist!=None:
            self._arg = self._nodelist.render(context);
            
        try:
            exec self._arg.strip() in env;
        except Exception,msg:
            return str(msg);

        for var in env.keys():
            context[var] = env[var];            
        return '';
    
def do_exec(parser, token):
    bits = token.contents.split()
    code = '';
    if len(bits)==1:
        nodelist = parser.parse(('endexec',))
        parser.delete_first_token();
        return ExecNode('', nodelist);
    else:
        tagname, code = token.contents.split(None, 1);
 
    return ExecNode(code);
 
tag_exec = register.tag('exec' , do_exec )

More like this

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

Comments

wiz (on April 2, 2007):

Recite the "Django is not PHP" mantra until enlightenment.

q:

#

skam (on April 2, 2007):

Please do not post this kind of snippets. You are using Django, not PHP. Really bad!

#

aquila (on April 2, 2007):

It just means a capacity, how to use is up to you, maybe someday you'll need it .

#

jcroft (on April 2, 2007):

If you want Python in templates, you could use Cheetah or similar. Django templates are specifically designed to not include Python code -- so while I can see how this might be useful to you, it feels very against the "Django way."

Certainly nothing wrong with you doing it and posting it, though -- but most Djangoers won't appreciate this approach, I'm afraid.

#

Magus (on April 4, 2007):

If you need advanced things in a template, make custom tags - don't use something like this to let you use raw code in them.

#

Please login first before commenting.