import jinja2
from jinja2.utils import Markup, escape

from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaulttags import CsrfTokenNode

from chouwa.decorators import jinjaglobal, jinjafilter

@jinjaglobal
@jinja2.contextfunction
def csrf_token_tag(context):
    return Markup(CsrfTokenNode().render(context))


@jinjaglobal
def url(viewname, *args, **kwargs):
    '''
    Lookup a url via `django.core.urlresolvers.reverse`.

    :Parameters:
      viewname : str
        The label associated with a url or the dotted path module name
        of a view.
    '''
    return reverse(viewname, settings.ROOT_URLCONF, args, kwargs)


@jinjafilter
def linebreaksbr(value):
    escaped_lines = []
    for line in value.split('\n'):
        escaped_lines.append(escape(line))
    escaped = "<br/>".join(escaped_lines)
    return Markup(escaped)



@@ -134,63 +134,8 @@
 ngs%0D
-%0Afrom django.template.defaulttags import CsrfTokenNode%0D
 %0A%0D%0Af
@@ -268,53 +268,249 @@
     
-return Markup(CsrfT
+csrf_token = context.get('csrf_token', None)%0D%0A    code = ''%0D%0A    if csrf_token:%0D%0A        if csrf_t
 oken
-Node().render(context)
+ != 'NOTPROVIDED':%0D%0A            code = '%3Cinput type=%22hidden%22 name=%22csrfmiddlewaretoken%22 value=%22%25s%22 /%3E' %25 csrf_token%0D%0A    return Markup(code
 )%0D%0A%0D

correct html in csrf tag