composer require artack/svg-inline-bundle
config/bundles.php:
Artack\SvgInlineBundle\SvgInlineBundle::class => ['all' => true],
config/packages/artack_svg_inline.yaml:
svg_inline:
path: "%kernel.project_dir%/assets/svg" # Adjust path to your SVG directory
{{ svg_inline('logo.svg') }}
Embedding SVGs
Use the svg_inline() Twig function to replace <img> tags with inline SVG:
{{ svg_inline('icon.svg', { class: 'icon', width: 24, height: 24 }) }}
Renders as:
<svg class="icon" width="24" height="24" ...>...</svg>
Dynamic Paths Override the base path per template:
{{ svg_inline('custom.svg', { path: 'assets/custom-svgs' }) }}
Reusable Components Combine with Twig includes for modular icons:
{% include 'components/icon.html.twig' with { name: 'twitter.svg', size: '2x' } %}
Path Resolution
Ensure svg_inline.path in config points to an absolute directory (relative paths may fail in production).
Fix: Use %kernel.project_dir% for reliability.
SVG Validation Malformed SVGs (e.g., unclosed tags) will break rendering. Validate files pre-commit:
composer require --dev squizlabs/php_codesniffer
vendor/bin/phpcs --standard=PSR12 assets/svg/*.svg
Twig Autoloading
If svg_inline() fails, verify Twig’s loader includes the bundle’s templates:
// config/packages/twig.yaml
twig:
paths: ['%kernel.project_dir%/vendor/artack/svg-inline-bundle/Resources/views']
Check Logs
Enable debug mode (APP_DEBUG=true) to log missing SVG files:
# config/packages/monolog.yaml
handlers:
main:
level: debug
Verify File Permissions Ensure the SVG directory is readable by the web server:
chmod -R 755 assets/svg
Custom Filters Extend the bundle by adding Twig filters to modify SVG output:
{{ svg_inline('logo.svg')|svg_add_viewbox('0 0 100 100') }}
Implementation: Override the bundle’s SvgInlineExtension class.
Dynamic Attributes
Use Twig’s merge to append attributes dynamically:
{% set attrs = { 'aria-label': 'Close', 'role': 'button' } %}
{{ svg_inline('close.svg', attrs|merge({ class: 'btn-icon' })) }}
Fallback for Missing SVGs Handle missing files gracefully:
{% if svg_inline('missing.svg') is not empty %}
{{ svg_inline('missing.svg') }}
{% else %}
<span class="svg-fallback">✕</span>
{% endif %}
How can I help you explore Laravel packages today?