Skip to content

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.

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.

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'}) }}

Use icon_exists() to guard against missing icons:

{% if icon_exists('heroicons:user') %}
{{ icon('heroicons:user') }}
{% endif %}

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.

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 (...) --> #}

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 #}
  • Fluent API: full reference for Icon methods like size(), class(), and fill()
  • Accessibility: decorative vs meaningful icons and ARIA attributes