# Author: aquila (tychen81@163.com)

"""
    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 )