Skip to content

Instantly share code, notes, and snippets.

@chrisvoncsefalvay
Created September 27, 2016 21:29
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 chrisvoncsefalvay/ba01ac7ecf2cea9e9dcf5c7d2246fe8d to your computer and use it in GitHub Desktop.
Save chrisvoncsefalvay/ba01ac7ecf2cea9e9dcf5c7d2246fe8d to your computer and use it in GitHub Desktop.
Insert SVG as <object> in Django
{% load i18n static template_tags %}
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>This is an SVG, inserted as an object.</h1>
{% svgobject 'images/svg/test.svg' 'test-class-one' 'test-class-two' %}
</body>
</html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>This is an SVG, inserted as an object.</h1>
<object class="test-class-one test-class-two" type="image/svg+xml" data="http://www.example.com/static/images/svg/test.svg"></object>
</body>
</html>
from django import template
from django.templatetags.static import static
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def svgobject(path, *args):
"""
Creates a template tag {% svgobject [path] <classes...> %} that embeds an SVG object within the `static` root as an
`image/svg+xml` object.
:param path: path of image within the `static` root
:type path: str
:param args: list of optional classes to append - these will be appended to the object class, not a container or
any specific subclass of the svg!
:type args: tuple
:return: HTML `object` tag representing the image with the requisite tags
:rtype: str
"""
link = static(path)
if len(args) > 0:
classes = ' '.join(args)
else:
classes = ""
return mark_safe("""<object class="{classes}" type="image/svg+xml" data="{url}"></object>""".format(
classes=classes,
url=link
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment