Twig Integration
If you’re using Twig, Swarm Icons gives you three template functions that make working with icons feel native. No |raw filters, no PHP includes, just clean template syntax.
Register the extension
Section titled “Register the extension”Wire up the extension with your Twig environment:
use Frostybee\SwarmIcons\Twig\SwarmIconsExtension;use Frostybee\SwarmIcons\Twig\SwarmIconsRuntime;
$twig->addExtension(new SwarmIconsExtension( new SwarmIconsRuntime($manager)));That’s all the PHP you need. Everything else happens in your templates.
Rendering icons
Section titled “Rendering icons”The icon() function outputs a full <svg> tag. It’s marked as HTML-safe, so Twig won’t escape it:
{{ icon('heroicons:home') }}{{ icon('heroicons:home', {class: 'w-6 h-6', 'aria-label': 'Home'}) }}Checking if an icon exists
Section titled “Checking if an icon exists”Use icon_exists() to guard against missing icons:
{% if icon_exists('heroicons:user') %} {{ icon('heroicons:user') }}{% endif %}Fluent manipulation
Section titled “Fluent manipulation”When you need more control, get_icon() returns the Icon object so you can chain methods directly in the template:
{% set star = get_icon('heroicons:star') %}{{ star.size(32).class('text-yellow-500') }}
{{ get_icon('tabler:arrow-right').fill('currentColor').strokeWidth(1.5) }}If silentOnMissing is enabled (see below), get_icon() returns null when the icon isn’t found.
Handling missing icons gracefully
Section titled “Handling missing icons gracefully”By default, a missing icon throws an exception. If you’d rather fail silently, enable silentOnMissing: missing icons render as an HTML comment instead:
$twig->addExtension(new SwarmIconsExtension( new SwarmIconsRuntime($manager, silentOnMissing: true)));{{ icon('heroicons:nonexistent') }}{# → <!-- SwarmIcons: Icon 'heroicons:nonexistent' not found (...) --> #}A note on naming
Section titled “A note on naming”Keeping templates clean
Section titled “Keeping templates clean”The real power shows up when you combine Twig with config-level defaults. Set your sizes and styles once:
SwarmIconsConfig::create() ->defaultAttributes(['class' => 'h-6 w-6']) ->defaultPrefix('tabler') ->build();And your templates stay minimal:
{{ icon('plus') }}{{ icon('home') }}{{ icon('user') }}Every icon gets class="h-6 w-6" automatically. Override only when you need something different:
{{ icon('logo', {class: 'h-12 w-12'}) }}If different sets need different styling, use prefix defaults:
->prefixAttributes('tabler', ['class' => 'h-6 w-6', 'stroke-width' => '1.5'])->prefixAttributes('heroicons', ['class' => 'h-5 w-5']){{ icon('tabler:home') }} {# h-6 w-6, stroke-width 1.5 #}{{ icon('heroicons:check') }} {# h-5 w-5 #}See also
Section titled “See also”- Fluent API: full reference for
Iconmethods likesize(),class(), andfill() - Accessibility: decorative vs meaningful icons and ARIA attributes