Example #1
0
def brick_table_data_status(parser, token):
    """Mark some <td> in table-bricks with specific HTML attribute.

    Generally markers are 'primary' and 'action', but you can use your own.

    Example:
        {% extends 'creme_core/bricks/base/table.html' %}
        {% load creme_bricks %}

        ...

        {% block brick_table_rows %}
            <tr>
                <td {% brick_table_data_status primary %}> ... </td> {# Will have "data-table-primary-column" attribute #}
                ...
            </tr>
        {% endblock %}
    """
    tokens = token.split_contents()  # Splitting by None == splitting by spaces.

    if len(tokens) < 2:
        raise TemplateSyntaxError('"{!r}" tag requires at least one argument.'.format(tokens[0]))

    return TextNode(' '.join('data-table-{}-column'.format(t) for t in tokens[1:]))
Example #2
0
 def nevercache(parser, token):
     """
     Tag for two phased rendering. Converts enclosed template
     code and content into text, which gets rendered separately
     in ``mezzanine.core.middleware.UpdateCacheMiddleware``.
     This is to bypass caching for the enclosed code and content.
     """
     text = []
     end_tag = "endnevercache"
     tag_mapping = {
         TOKEN_TEXT: ("", ""),
         TOKEN_VAR: ("{{", "}}"),
         TOKEN_BLOCK: ("{%", "%}"),
         TOKEN_COMMENT: ("{#", "#}"),
     }
     delimiter = nevercache_token()
     while parser.tokens:
         token = parser.next_token()
         token_type = token.token_type
         if token_type == TOKEN_BLOCK and token.contents == end_tag:
             return TextNode(delimiter + "".join(text) + delimiter)
         start, end = tag_mapping[token_type]
         text.append("%s%s%s" % (start, token.contents, end))
     parser.unclosed_block_tag(end_tag)
Example #3
0
 def process_node_list(self, nodelist, context):
     new_nodes = NodeList()
     variable_nodes = []
     i = nodelist.__len__() - 1
     l = 0
     while l <= i:
         while l <= i:
             this_node = nodelist[l]
             node_class = this_node.__class__.__name__
             if node_class == "ForNode":
                 this_node = self.assemble_for_node(this_node, context)
             if node_class == "IfNode":
                 this_node = self.assemble_if_node(this_node, context)
             if node_class == 'TextNode':
                 splitted = self.split_text_node(this_node.s)
                 for item in splitted:
                     new_nodes.append(item)
             else:
                 new_nodes.append(this_node)
             if "VariableNode" in node_class:
                 variable_nodes.append(new_nodes.__len__() - 1)
             l = l + 1
         schema_props = []
         for item in variable_nodes:
             node_in_question = new_nodes[item]
             schema_prop = ''
             if hasattr(node_in_question, 'filter_expression'):
                 filter_exp = str(node_in_question.filter_expression)
                 filter_exp = filter_exp.replace(self.object_name + '.', '')
                 # ensure ones with added template tags work properly
                 if '|' in filter_exp:
                     filter_exp = filter_exp[:filter_exp.find('|')]
                 try:
                     schema_prop = schemaprop(self.obj, filter_exp, item)
                 except:
                     e = sys.exc_info()[0]
                     raise TemplateSyntaxError(e)
                 schema_props.append(schema_prop)
         prop_count = schema_props.__len__() - 1
         prop_index = 0
         while prop_index <= prop_count:
             prior_node_counter = 1
             this_prop = schema_props[prop_index]
             prior_node = new_nodes[this_prop.variable_node - prior_node_counter]
             found_prior = False
             while not (found_prior or (prior_node_counter == this_prop.variable_node)):
                 if prior_node.__class__.__name__ == 'CloseTagNode':
                     prior_node.s = ' ' + str(this_prop) + prior_node.s
                     found_prior = True
                 elif prior_node.__class__.__name__ == 'OpenVoidNode':
                     found_prior = True
                     prior_node.s = prior_node.s + str(this_prop) + ' '
                 elif prior_node.__class__.__name__ == 'OpenTagNode':
                     found_prior = True
                 else:
                     prior_node_counter = prior_node_counter + 1
                     prior_node = new_nodes[this_prop.variable_node - prior_node_counter]
             prop_index = prop_index + 1
         scope = schemascope(self.obj)
         top_text = "<" + self.html_class + ' '
         if self.html_attribute:
             top_text = top_text + self.html_attribute
         if self.id_attr:
             top_text = top_text + ' id="#' + self.id_attr + str(self.obj.pk) + '"'
         top_text = top_text + ' itemscope itemtype=' + scope + '>'
         bottom_text = "</" + self.html_class + ">"
         topnode = TextNode(top_text)
         bottomnode = TextNode(bottom_text)
         new_nodes.insert(0, topnode)
         new_nodes.append(bottomnode)
     return new_nodes
Example #4
0
def compress(context, data, name):
    """
    Data is the string from the template (the list of js files in this case)
    Name is either 'js' or 'css' (the sekizai namespace)
    Basically passes the string through the {% compress 'js' %} template tag
    Alternatively, if the block can contain a html comment structured like:
    <!-- compress_options [params] -->
    params can be: one of ['js','css'] and one or multiple of ['file','preload','inline']
    """
    # separate compressable from uncompressable files
    options = []
    kind = name
    m = re.search('<!-- *compress_options *([a-z ]+?) *-->', data)
    if m is not None:
        options_clean = re.sub(' +', ' ', m.groups()[0])
        options = set(options_clean.split(' '))
        if 'js' in options and 'css' not in options:
            kind = 'js'
        elif 'css' in options and 'js' not in options:
            kind = 'css'

    parser = get_class(settings.COMPRESS_PARSER)(data)
    js_compressor, css_compressor = Compressor('js'), Compressor('css')
    compressable_elements, expanded_elements, deferred_elements = [], [], []
    if kind == 'js':
        for elem in parser.js_elems():
            attribs = parser.elem_attribs(elem)
            try:
                if 'src' in attribs:
                    js_compressor.get_basename(attribs['src'])
            except UncompressableFileError:
                if 'defer' in attribs:
                    deferred_elements.append(elem)
                else:
                    expanded_elements.append(elem)
            else:
                compressable_elements.append(elem)
    elif kind == 'css':
        for elem in parser.css_elems():
            attribs = parser.elem_attribs(elem)
            try:
                if parser.elem_name(elem) == 'link' and attribs['rel'].lower(
                ) == 'stylesheet':
                    css_compressor.get_basename(attribs['href'])
            except UncompressableFileError:
                expanded_elements.append(elem)
            else:
                compressable_elements.append(elem)

    # reconcatenate them
    results = []
    data = ''.join(parser.elem_str(e) for e in expanded_elements)
    expanded_node = CompressorNode(nodelist=TextNode(data),
                                   kind=kind,
                                   mode='file')
    results.append(expanded_node.get_original_content(context=context))

    if 'file' in options or len(options) == 0:
        data = ''.join(parser.elem_str(e) for e in compressable_elements)
        compressable_node = CompressorNode(nodelist=TextNode(data),
                                           kind=kind,
                                           mode='file')
        tmp_result = compressable_node.render(context=context)
        if 'defer' in options:
            tmp_result = re.sub("></script>$", " defer=\"defer\"></script>",
                                tmp_result)
        results.append(tmp_result)

    if 'preload' in options:
        data = ''.join(parser.elem_str(e) for e in compressable_elements)
        compressable_node = CompressorNode(nodelist=TextNode(data),
                                           kind=kind,
                                           mode='preload')
        results.append(compressable_node.render(context=context))

    if 'inline' in options:
        data = ''.join(parser.elem_str(e) for e in compressable_elements)
        compressable_node = CompressorNode(nodelist=TextNode(data),
                                           kind=kind,
                                           mode='inline')
        results.append(compressable_node.render(context=context))

    data = ''.join(parser.elem_str(e) for e in deferred_elements)
    deferred_node = CompressorNode(nodelist=TextNode(data),
                                   kind=kind,
                                   mode='file')
    results.append(deferred_node.get_original_content(context=context))

    return '\n'.join(results)
Example #5
0
def date_format(parser, token):
    return TextNode(settings.DATE_FORMAT_JS)
Example #6
0
def verbatim_tags(parser, token, endtagname='', endtagnames=[]):
    """
    Javascript templates (jquery, handlebars.js, mustache.js) use constructs like:

    ::

        {{if condition}} print something{{/if}}

    This, of course, completely screws up Django templates,
    because Django thinks {{ and }} means something.

    The following code preserves {{ }} tokens.

    This version of verbatim template tag allows you to use tags
    like url {% url name %}. {% trans "foo" %} or {% csrf_token %} within.

    @returns a list of nodes.
    """

    nodelist = NodeList()
    while 1:
        token = parser.tokens.pop(0)

        if token.contents in endtagnames or token.contents == endtagname:
            break

        # special case, {{ block.super }} is something we don't want to escape!
        # TODO: refactor this condition, token.split_contents should return
        # only one string, block.super, otherwise we might be dealing with
        # handlebars templating shenanigans

        # FIXME: block.super not working

        # if 'block.super' in token.contents:
        #     filter_expression = parser.compile_filter(token.contents)
        #     var_node = parser.create_variable_node(filter_expression)
        #     parser.extend_nodelist(nodelist, var_node, token)
        #     import pdb; pdb.set_trace()

        if token.token_type == TOKEN_VAR:
            parser.extend_nodelist(nodelist, TextNode('{{'), token)
            parser.extend_nodelist(nodelist, TextNode(token.contents), token)

        elif token.token_type == TOKEN_TEXT:
            parser.extend_nodelist(nodelist, TextNode(token.contents), token)

        elif token.token_type == TOKEN_BLOCK:
            try:
                command = token.contents.split()[0]
            except IndexError:
                parser.empty_block_tag(token)

            try:
                compile_func = parser.tags[command]
            except KeyError:
                parser.invalid_block_tag(token, command, None)
            try:
                node = compile_func(parser, token)
            except template.TemplateSyntaxError, e:
                if not parser.compile_function_error(token, e):
                    raise
            parser.extend_nodelist(nodelist, node, token)

        if token.token_type == TOKEN_VAR:
            parser.extend_nodelist(nodelist, TextNode('}}'), token)
Example #7
0
def version(parser, token):
    return TextNode(util.version())