Skip to content

Instantly share code, notes, and snippets.

@piotrpog piotrpog/favicons.twig
Last active Sep 30, 2019

Embed
What would you like to do?
Twig component generating favicons from files uploaded trough control panel. More info: http://craftsnippets.com/articles/adding-favicons-to-craft-cms-website
{# requires global with handle 'favicon' containing asset field with handle 'faviconFile' #}
{# v2 #}
{% cache globally %}
{% set sizesIcon = [192, 48, 32, 16] %}
{% set sizesAppleTouch = [180] %}
{% if favicon is defined and favicon['faviconFile'] is defined and favicon.faviconFile.exists() and favicon.faviconFile.one().kind == 'image' %}
{# link icon #}
{% for faviconSize in sizesIcon %}
{% set icon = favicon.faviconFile.one() %}
{% set shorterEdge = icon.width > icon.height ? icon.height : icon.width %}
{% if shorterEdge >= faviconSize %}
{% set faviconTransform = {
width: faviconSize,
height: faviconSize,
quality: 100,
position: 'center-center',
format: 'png',
} %}
{{tag('link', {
rel: 'icon',
sizes: faviconSize~'x'~faviconSize,
type: 'image/png',
href: icon.getUrl(faviconTransform),
}) }}
{% endif %}
{% endfor %}
{# link touch icon #}
{% for faviconSize in sizesAppleTouch %}
{% set icon = favicon.faviconFile.one() %}
{% set shorterEdge = icon.width > icon.height ? icon.height : icon.width %}
{% if shorterEdge >= faviconSize %}
{% set faviconTransform = {
width: faviconSize,
height: faviconSize,
quality: 100,
position: 'center-center',
format: 'png',
} %}
{{tag('link', {
rel: 'apple-touch-icon',
sizes: faviconSize~'x'~faviconSize,
href: icon.getUrl(faviconTransform),
}) }}
{% endif %}
{% endfor %}
{% endif %}
{% endcache %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.