A simple Twig extension for Craft CMS to create base64-encoded strings from Craft Assets in your Twig templates.
- Download the
.zipand copy theCraft-Twig-ImageBase64directory into your Craftpluginsdirectory. - Rename the
Craft-Twig-ImageBase64directory toimagebase64. - Login to your Craft control panel, navigate to
Pluginsand enableImage Base 64. - Use the
{{ image64(asset) }}in your Twig templates to output a base64-encoded string from your Craft Asset. - You're done!
This Twig extension requires that you pass an instance of Craft's AssetFileModel in your Twig template.
The extension can be used as either a Twig filter or as a Twig extension.
{{ image64(asset) }}
{{ image64(asset, true) }}
This will return the base64-encoded string in a data URI scheme.
{{ asset|image64 }}
Note: In either case, asset must be an instance of Craft's AssetFileModel. The extension will die gracefully if anything other than that is passed in as the first parameter.
default = false
Setting the inline parameter to true will return a base64-encoded string as a data URI scheme. Use this option when setting an <img> src or background-image in CSS.
<img src="{{ image64(asset) }}" alt="Rad Dad!">
You can optionally use the extension as a filter instead of a function:
<img src="{{ asset|image64 }}" alt="Rad Dad!">
{% for asset in entry.assets %}
<img src="{{ image64(asset, true) }}" alt="A rad base64-encoded image with a data URI scheme!">
{% endfor %}
Note: In all examples, asset must be an instance of Craft's AssetFileModel. The extension will die gracefully if anything other than that is passed in as the first parameter.