Beispiel #1
0
        def templatetag_raw(parser, token):
            """
            Return a TextNode with all html not parsed, used for templatetags
            that need to not be parsed : the `nocache` one and the `RAW` one,
            used to surround cached html (to be not parsed again)
            Based on http://www.holovaty.com/writing/django-two-phased-rendering/
            """

            # Whatever is between {% nocache %} and {% endnocache %} will be preserved as
            # raw, unrendered template code.

            text = []
            parse_until = 'end%s' % token.contents
            tag_mapping = {
                template.TOKEN_TEXT: ('', ''),
                template.TOKEN_VAR: ('{{', '}}'),
                template.TOKEN_BLOCK: ('{%', '%}'),
                template.TOKEN_COMMENT: ('{#', '#}'),
            }
            # By the time this template tag is called, the template system has already
            # lexed the template into tokens. Here, we loop over the tokens until
            # {% endraw %} and parse them to TextNodes. We have to add the start and
            # end bits (e.g. "{{" for variables) because those have already been
            # stripped off in a previous part of the template-parsing process.
            while parser.tokens:
                token = parser.next_token()
                if token.token_type == template.TOKEN_BLOCK and token.contents == parse_until:
                    return template.TextNode(u''.join(text))
                start, end = tag_mapping[token.token_type]
                text.append(u'%s%s%s' % (start, token.contents, end))
            parser.unclosed_block_tag(parse_until)
Beispiel #2
0
 def raw(parser, token):
     # Whatever is between {% verbatim %} and {% endverbatim %}
     # will be preserved as
     # verbatim, unrendered template code.
     text = []
     parse_until = 'endverbatim'
     tag_mapping = {
         template.TOKEN_TEXT: ('', ''),
         template.TOKEN_VAR: ('{{', '}}'),
         template.TOKEN_BLOCK: ('{%', '%}'),
         template.TOKEN_COMMENT: ('{#', '#}'),
     }
     # By the time this template tag is called, the template
     # system has already lexed the template into tokens.
     # Here, we loop over the tokens until
     # {% endverbatim %} and parse them to TextNodes.
     # We have to add the start and
     # end bits (e.g. "{{" for variables) because those 
     # have already been stripped off in a previous
     # part of the template-parsing process.
     while parser.tokens:
         token = parser.next_token()
         if token.token_type == template.TOKEN_BLOCK and \
                 token.contents == parse_until:
             return template.TextNode(u''.join(text))
         start, end = tag_mapping[token.token_type]
         if token.contents.startswith('='):
             text.append(u'%s%s %s' % (start, token.contents, end))
         else:
             text.append(u'%s %s %s' % (start, token.contents, end))
     parser.unclosed_block_tag(parse_until)
Beispiel #3
0
def app_installed(parser, token):
    """
    Check if app with given name installed:
        {% app 'app.plugins.app' %}
            ...
        {% elseapp %}
            ...
        {% endapp %}
    """
    tag_name, app_name = token.split_contents()
    app_name = app_name[1:-1]

    if app_name in settings.INSTALLED_APPS:
        nodelist_true = parser.parse(('elseapp', 'endapp'))
        token = parser.next_token()
        if token.contents == 'elseapp':
            parser.skip_past('endapp')
        return AppNode(nodelist_true, app_name)
    while parser.tokens:
        token = parser.next_token()
        if token.token_type == 2 and token.contents in ('elseapp', 'endapp'):
            break
    if token.contents == 'elseapp':
        nodelist_false = parser.parse(('endapp', ))
        parser.delete_first_token()
    else:
        return template.TextNode('')

    return AppNode(nodelist_false, app_name)
Beispiel #4
0
def raw(parser, token):
    # Whatever is between {% raw %} and {% endraw %} will be preserved as
    # raw, unrendered template code.
    # If 'silent' is passed in -- {% raw silent %} -- then the resulting output
    # will not contain the {% raw %} and {% endraw %} tags themselves.
    # Otherwise, the output will include an {% endraw %} at the start and
    # {% raw %} at the end, so that other parts of the page aren't vulnerable
    # to Django template escaping injection.
    silent = 'silent' in token.contents
    if silent:
        text = []
    else:
        text = ['{% endraw %}']
    parse_until = 'endraw'
    tag_mapping = {
        template.TOKEN_TEXT: ('', ''),
        template.TOKEN_VAR: ('{{', '}}'),
        template.TOKEN_BLOCK: ('{%', '%}'),
        template.TOKEN_COMMENT: ('{#', '#}'),
    }
    # By the time this template tag is called, the template system has already
    # lexed the template into tokens. Here, we loop over the tokens until
    # {% endraw %} and parse them to TextNodes. We have to add the start and
    # end bits (e.g. "{{" for variables) because those have already been
    # stripped off in a previous part of the template-parsing process.
    while parser.tokens:
        token = parser.next_token()
        if token.token_type == template.TOKEN_BLOCK and token.contents == parse_until:
            if not silent:
                text.append('{% raw silent %}')
            return template.TextNode(u''.join(text))
        start, end = tag_mapping[token.token_type]
        text.append(u'%s%s%s' % (start, token.contents, end))
    parser.unclosed_block_tag(parse_until)
Beispiel #5
0
def do_static_nonce(parser, token):
    tokens = token.split_contents()
    if len(tokens) > 2 or not quoted_attribute(tokens[1]):
        raise template.TemplateSyntaxError(
            'syntax is {% static_nonce "<file_name>" %}')
    filename = unquote_attribute(tokens[1])
    fullpath = os.path.join(settings.STATIC_DIR, filename)
    if not os.path.exists(fullpath):
        raise template.TemplateSyntaxError('%s does not exist' % filename)
    nonce = hash(os.stat(fullpath))
    return template.TextNode('%s%s?%i' %
                             (settings.STATIC_BASE_URL, filename, nonce))
Beispiel #6
0
def simile(parser, token, apps, forceBundle=False):
    """Generic function for simile api inclusions
    """

    args = token.split_contents()[1:]
    simileurl = reverse('static', kwargs={'path': 'simile/'})
    opts = {'bundle': 'true', 'autoCreate': 'true'}
    for arg in args:
        try:
            k, v = arg.split('=', 1)
            if k in opts:
                opts[k] = v
        except ValueError:
            pass
    bundle = opts['bundle'] == 'false' and 'bundle=false' or None
    if bundle is None and forceBundle:
        bundle = 'bundle=true'
    autoCreate = opts['autoCreate'] == 'false' and 'autoCreate=false' or None
    ajax_params = '&'.join(filter(None, [bundle]))
    if ajax_params:
        ajax_params = '?' + ajax_params
    app_params = '&'.join(filter(None, [bundle, autoCreate]))
    if app_params:
        app_params = '?' + app_params
    script_head = '''<script type="text/javascript">
(function() {
  '''
    script_tail = '''
})();
</script>
<script type="text/javascript" '''\
'''src="%(base)sajax/simile-ajax-api.js%(params)s"></script>
''' % {'base': simileurl, 'params': ajax_params}
    loaders = []
    next = None
    params = app_params
    for app in reversed(apps):
        loaders += ['function load_%s() {' % app]
        if next is not None:
            loaders += ['  window.SimileAjax_onLoad = load_%s;' % next]
        loaders += [
            '  SimileAjax.includeJavascriptFile(document, "%(base)s%(app)s/'\
            '%(app)s-api.js%(params)s");' % \
            {'base': simileurl, 'app': app, 'params': params},
            '};']
        next = app
        params = ajax_params
    loaders += ['window.SimileAjax_onLoad = load_%s;' % next]
    out = (script_head + '\n  '.join(loaders) + script_tail)
    return template.TextNode(out)
Beispiel #7
0
def do_include_raw(parser, token):
    """
    Performs a template include without parsing the context, just dumps the template in.
    """
    bits = token.split_contents()
    if len(bits) != 2:
        raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0]

    template_name = bits[1]
    if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]:
        template_name = template_name[1:-1]

    source, path = load_template_source(template_name)

    return template.TextNode(source)
Beispiel #8
0
def do_include_ich(parser, token):
    bits = token.split_contents()
    template_name = bits[1]
    if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]:
        template_name = template_name[1:-1]

    block_name, block_type = basename(template_name).rsplit('.', 1)
    source, path = _loader.load_template_source(template_name)

    render = '<script id="tpl_%s" type="text/%s">\n%s\n</script>' % (block_name, block_type, source)

    if 'partial' in bits:
        render += '<script id="tpl_partial_%s" type="text/%s" class="partial">\n%s\n</script>' % (block_name, block_type, source)

    return template.TextNode(render)
Beispiel #9
0
 def __init__(self, var_user, var_entry, is_admin, pred, api_call,
              link_class, content):
     self.var_user = template.Variable(var_user)
     self.var_entry = template.Variable(var_entry)
     self.var_is_admin = None
     try:
         template.Variable(is_admin)
     except:
         pass
     self.pred = pred
     self.api_call = api_call
     self.link_class = link_class
     if not isinstance(content, template.Node):
         self.content = template.TextNode(content)
     else:
         self.content = content
Beispiel #10
0
def do_include_raw(parser, token):
    """
    Performs a template include without parsing the context, just dumps
    the template in.
    Source: http://djangosnippets.org/snippets/1684/
    """
    bits = token.split_contents()
    if len(bits) != 2:
        raise template.TemplateSyntaxError(
            "%r tag takes one argument: the name of the template "
            "to be included" % bits[0]
        )

    template_name = bits[1]
    if template_name[0] in ('"', "'") and template_name[-1] == template_name[0]:
        template_name = template_name[1:-1]

    source, path = Loader.load_template_source(template_name)

    return template.TextNode(source)
Beispiel #11
0
def do_include_raw(parser, token):
    """Perform a raw template include.

    This means to include the template without parsing context, just dump the
    template in.

    Source: http://djangosnippets.org/snippets/1684/
    """
    bits = token.split_contents()
    if len(bits) != 2:
        excp_msg = ("%r tag takes one argument: the name of the template to "
                    "be included" % bits[0])
        raise template.TemplateSyntaxError(excp_msg)

    template_name = bits[1]
    if (template_name[0] in ('"', "'")
            and template_name[-1] == template_name[0]):
        template_name = template_name[1:-1]

    template_loader = Loader()
    source, path = template_loader.load_template_source(template_name)

    return template.TextNode(source)
Beispiel #12
0
def raw(parser, token):
    # Whatever is between {% raw %} and {% endraw %} will be preserved as
    # raw, unrendered template code.
    text = []
    parse_until = "endraw"
    tag_mapping = {
        template.TOKEN_TEXT: ("", ""),
        template.TOKEN_VAR: ("{{", "}}"),
        template.TOKEN_BLOCK: ("{%", "%}"),
        template.TOKEN_COMMENT: ("{#", "#}"),
    }
    # By the time this template tag is called, the template system has already
    # lexed the template into tokens. Here, we loop over the tokens until
    # {% endraw %} and parse them to TextNodes. We have to add the start and
    # end bits (e.g. "{{" for variables) because those have already been
    # stripped off in a previous part of the template-parsing process.
    while parser.tokens:
        token = parser.next_token()
        if token.token_type == template.TOKEN_BLOCK and token.contents == parse_until:
            return template.TextNode(u"".join(text))
        start, end = tag_mapping[token.token_type]
        text.append(u"%s%s%s" % (start, token.contents, end))
    parser.unclosed_block_tag(parse_until)
Beispiel #13
0
def raw(parser, token):
    # ro: thanks to EveryBlock for this code snippet
    # Whatever is between {% raw %} and {% endraw %} will skip the cache
    # so that e.g. 'usernames' can be refreshed while reports remain cached
    text = []
    parse_until = 'endraw'
    tag_mapping = {
        template.TOKEN_TEXT: ('', ''),
        template.TOKEN_VAR: ('{{', '}}'),
        template.TOKEN_BLOCK: ('{%', '%}'),
        template.TOKEN_COMMENT: ('{#', '#}'),
    }
    # By the time this template tag is called, the template system has already
    # lexed the template into tokens. Here, we loop over the tokens until
    # {% endraw %} and parse them to TextNodes. We have to add the start and
    # end bits (e.g. "{{" for variables) because those have already been
    # stripped off in a previous part of the template-parsing process.
    while parser.tokens:
        token = parser.next_token()
        if token.token_type == template.TOKEN_BLOCK and token.contents == parse_until:
            return template.TextNode(u''.join(text))
        start, end = tag_mapping[token.token_type]
        text.append(u'%s%s%s' % (start, token.contents, end))
    parser.unclosed_block_tag(parse_until)
Beispiel #14
0
def make_text_or_variable_node(parser, expression):
    if quoted_attribute(expression):
        return template.TextNode(unquote_attribute(expression))
    else:
        return template.VariableNode(parser.compile_filter(expression))