Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active September 30, 2019 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotrpog/ed5a3a21e792e0d46dd766b4d2220913 to your computer and use it in GitHub Desktop.
Save piotrpog/ed5a3a21e792e0d46dd766b4d2220913 to your computer and use it in GitHub Desktop.
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