Skip to content

Instantly share code, notes, and snippets.

@fvsch
Created June 20, 2018 12:35
Show Gist options
  • Save fvsch/d18ccb3ca515caefce96354b868375ed to your computer and use it in GitHub Desktop.
Save fvsch/d18ccb3ca515caefce96354b868375ed to your computer and use it in GitHub Desktop.
Twig macro and default style for SVG icons
/**
* Default style for SVG icons
*/
.icon {
/* Allows sizing by changing the icon’s font-size.
(It should override the element's width/height attributes, if they exist.) */
width: 1em;
height: 1em;
/* This prevents having extra space below icons, and can be overriden easily
to vertical-align:middle or vertical-align:-0.3em if needed. */
vertical-align: top;
/* Default path fill = value of the color property. */
fill: currentColor;
/* SVG elements may intercept click events in IE11.
Let click events go through to a parent link or button instead. */
pointer-events: none;
}
{#
Macro for using SVG icons from a SVG symbol sprite
Learn more: https://fvsch.com/code/svg-icons/
Usage:
{{ icon('name') }}
{{ icon('name', {url: '/path/to/sprite.svg#icon-%s', width: 64}) }}
If you want to define a base URL and size for all icons, you could define
a 'default_icon_settings' global variable in your Twig environement:
twig:
globals:
default_icon_settings:
url: '/my/url/pattern/sprite.svg#prefix-%s'
width: 24
Code notes:
1. Hide from screen readers; provide alt text in a visually hidden element.
2. Prevents IE11 from adding this icon to the tab order.
3. Fixes a Safari bug where focus gets trapped in the SVG!
#}
{% macro icon(name, settings) %}
{% spaceless %}
{% set settings = settings ?? default_icon_settings ?? {} %}
{% set url = settings.url ?? '#icon-%s' %}
{% set width = settings.width ?? 16 %}
{% set height = settings.height ?? width %}
<svg class="icon icon-{{name}}" aria-hidden="true"{#1#} focusable="false"{#2#}
{%- if width %} width="{{ width }}" height="{{ height }}"{% endif %}>
<use xlink:href="{{ url|format(name) }}"></use>
<g></g>{#3#}
</svg>
{% endspaceless %}
{% endmacro %}

Output for icon('menu'):

<svg class="icon icon-menu" aria-hidden="true" focusable="false" width="20" height="20"><use xlink:href="/dist/icons.svg#icon-menu"></use><g></g></svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment