How to output SVGs as code in Statamic's Antlers templating language
Because if you load them in with img tags, you lose half the power of SVGs.
Since originally writing this, I've built and released an addon specifically designed to help you output and control SVGs in Statamic. Check it out!
One of my favourite features of Twig is the {{ source }}
tag. It's effectively a wrapper for file_get_contents()
,
but exposed in a templating language. It's most useful when you're
looking to pull in an SVG into a template as code rather than an image.
Outputting SVGS in Statamic
I knew you could pull in SVGs within Statamic's Antlers templating language using the {{ theme:output src="" }}
tag. However, I was looking for a way to output an SVG as code when the
SVG is stored in an assets container in Antlers. Luckily, there is a
way.
It's the output modifier.
Let's say you have an SVG that is associated to a field called card_image
. Outputting the SVG that was uploaded to that field is as simple as calling it like so:
{{ card_image | output }}
This technique will of course work with other file types too, so it's probably worth ensuring that there's some validation to make sure only the type of file you want outputting is output.