Login

Tag that parses dict like format and convert to classes like AngularJS

Author:
bram2w
Posted:
May 11, 2016
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

This tag is inspired by how ng-class works in AngularJS. https://docs.angularjs.org/api/ng/directive/ngClass

example:

context = { 'context_var': True, 'context_var_2': 'a' }

{% classes "class_name_1": context_var == True, "class_name_2": context_var_2 == "a", "class_name_3": False %}

output: class_name_1 class_name_2

 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
from django.template import Library, Node
from django.template.defaulttags import TemplateIfParser
from django.template.base import TemplateSyntaxError, VariableDoesNotExist

register = Library()


def parse_classes(parser, content):
    classes_and_conditions = []
    classes_splitted = content.split(",")
    for class_value in classes_splitted:
        class_parts = class_value.split(":")
        if len(class_parts) != 2:
            raise TemplateSyntaxError("class must contain a name and condition")
        classes_and_conditions.append({
            'name': class_parts[0].replace("'", "").replace('"', "").strip(),
            'condition': TemplateIfParser(parser, class_parts[1].strip().split(" ")).parse()
        })
    return classes_and_conditions


class Classes(Node):
    classes = None

    def __init__(self, classes):
        self.classes = classes

    def render(self, context):
        classes_to_show = []
        for class_parts in self.classes:
            try:
                if class_parts['condition'].eval(context):
                    classes_to_show.append(class_parts['name'])
            except VariableDoesNotExist:
                pass
        return " ".join(classes_to_show)


def classes(parser, token):
    bits = token.split_contents()
    if len(bits[1:]) < 1:
        raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])

    offset = len(bits[0]) + 1
    return Classes(parse_classes(parser, token.contents[offset:]))


register.tag(classes)

More like this

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

Comments

Please login first before commenting.