1 icon.inc | theme_icon(array $variables) |
Returns HTML for an inline-icon.
This effectively returns the contents of an SVG file. But it could potentially be overridden to replace inlined SVGs with other mechanisms, like an icon font.
@since 1.28.0 Function added. @since 1.28.1 The <ellipse>, <line>, <polygon> and <polyline> SVG elements are allowed.
Parameters
array $variables: An associative array containing:
- name: The machine name for the icon being displayed.
- path: The full path to the icon file, relative to installation root.
- alt: Alternative text for this icon. Default icons are SVGs and this value is added as a <title> tag within the SVG. If not specified, the icon will automatically be assigned the aria-hidden="true" attribute.
- attributes: Attributes to be added to the icon itself.
Return value
string: The HTML output. An empty string if the icon file is not svg.
File
- core/
includes/ icon.inc, line 291 - Provides the Backdrop API for placing icons.
Code
function theme_icon(array $variables) {
// Ensure the filename is .svg.
if (image_is_svg($variables['path'])) {
// Ensure the file contents are an SVG.
$svg_contents = file_get_contents($variables['path']);
if (strpos($svg_contents, '<svg') === 0) {
// Allow basic shapes. See:
// https://developer.mozilla.org/en-US/docs/Web/SVG/Element#basic_shapes.
$allowed_svg_basic_shapes = array(
'circle',
'ellipse',
'line',
'polygon',
'polyline',
'rect',
);
// Allow some other elements. This very-restrictive set of options should
// be adequate for icons.
$allowed_svg_other = array(
'defs',
'desc',
'linearGradient',
'path',
'stop',
'svg',
'title',
'use',
);
$allowed_svg_elements = array_merge($allowed_svg_basic_shapes, $allowed_svg_other);
// Clean out any embedded XSS within the SVG.
$svg_contents = filter_xss($svg_contents, $allowed_svg_elements);
// Move the "alt" text to an attribute.
if ($variables['alt']) {
$variables['attributes']['alt'] = $variables['alt'];
}
else {
$variables['attributes']['aria-hidden'] = 'true';
}
// Add default icon classes.
$variables['attributes']['class'] = array_merge(
array('icon', 'icon--' . $variables['name']),
isset($variables['attributes']['class']) ? $variables['attributes']['class'] : array()
);
return image_add_svg_attributes($svg_contents, $variables['attributes']);
}
}
return '';
}