Last active
January 23, 2017 12:03
-
-
Save dennis90/1507a1b340a87f0ec768c91f9a9c1045 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from django.utils.safestring import mark_safe | |
from django import template | |
register = template.Library() | |
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') | |
@register.filter | |
def add_class(value, css_class): | |
string = str(value) | |
match = class_re.search(string) | |
if match: | |
m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, | |
css_class, css_class), match.group(1)) | |
print(match.group(1)) | |
if not m: | |
return mark_safe(class_re.sub(match.group(1) + " " + css_class, | |
string)) | |
else: | |
return mark_safe(string.replace('>', ' class="%s">' % css_class)) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment