Skip to content

Instantly share code, notes, and snippets.

@chrisma
Created June 9, 2015 09:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisma/dad9e71de343b4cd6e5c to your computer and use it in GitHub Desktop.
Save chrisma/dad9e71de343b4cd6e5c to your computer and use it in GitHub Desktop.
Django templatetag to convert hex to RGB colors.
# USAGE:
# {% load file_the_templatetag_is_in %}
# {{ my_hex_color| hex_to_rgb }}
# {{ my_hex_color| hex_to_rgb:'rgba({r},{g},{b}, 0.5)' }}
# {{ my_hex_color| hex_to_rgb:'Components: r:{r},g:{g},b:{b}' }}
# adapted from https://github.com/guillaumeesquevin/django-colors
@register.filter(name='hex_to_rgb')
def hex_to_rgb(hex, format_string='rgb({r},{g},{b})'):
"""Returns the RGB value of a hexadecimal color"""
hex = hex.replace('#','')
out = { 'r':int(hex[0:2], 16),
'g':int(hex[2:4], 16),
'b':int(hex[4:6], 16)}
return format_string.format(**out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment