from django import template

register = template.Library()


@register.filter
def percentage(value):
    try:
        value = float(value) * 100
        return f'{value:.0f}%'
    except (ValueError, TypeError):
        return value


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)


@register.filter(name='add_class')
def add_class(field, css_class):
    return field.as_widget(attrs={"class": css_class})


@register.filter(name='attr')
def attr(field, args):
    attrs = {}
    definitions = args.split(',')
    for definition in definitions:
        if ':' in definition:
            key, val = definition.split(':')
            attrs[key.strip()] = val.strip()
        else:
            attrs[definition.strip()] = True
    return field.as_widget(attrs=attrs)