Inline SVGs and templates

Say I have defined an SVG in static/mysvg.svg

How do I included it in my layout using templates as an inline.

Looking for something like this

index.html

<body>
{{ read_svg(mysvg.svg) }}
</body>

This should result in something like this

<body>
<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id="icon-brightness_mediumtheme-switch" viewBox="0 0 24 24">
<path d="M12 18q2.484 0 4.242-1.758t1.758-4.242-1.758-4.242-4.242-1.758v12zM20.016 15.328v4.688h-4.688l-3.328 3.281-3.328-3.281h-4.688v-4.688l-3.281-3.328 3.281-3.328v-4.688h4.688l3.328-3.281 3.328 3.281h4.688v4.688l3.281 3.328z"></path>
</symbol>
</defs>
</svg>
</body>

Hi vikigenius,

the function load_data can be used to load other files.
To prevent escaping you would have to use the “safe” filter.

{{ load_data(path="static/mysvg.svg") | safe}}

This is how i inline svg files.

1 Like

For extra points, you can even define a custom shortcode which could insert in other stuff as well.

For example, I almost always use svgs with captions, so my shortcode looks something like this:

{# Sample usage: {{ svgfigure(src="array-diagram.svg",
style="size-small center",
caption="An Array",
caption_style="font-weight: bold; font-style: italic;") }} #}

<figure class="{%- if class is defined -%}{{ class | safe }}{%- else -%} center {%- endif %}">
	{%- set src = "content" ~ page.path ~ src -%}
	{%- set svg = load_data(path=src, required=true) -%}
	<!--Add proper accessibility to svgs: https://stackoverflow.com/a/4756461/10147642 - if you're reading this in DevTools, and have an idea of how to, feel free to write to me!-->
	
	{{ svg | safe }}

	{% if caption %}
		<figcaption {% if caption_style %} style="{{ caption_style | safe }}"{% endif %}>{{ caption }}</figcaption>
	{% endif %}

</figure>