Skip to content

Instantly share code, notes, and snippets.

@LewisW
Created December 8, 2014 12:52
Show Gist options
  • Save LewisW/eb50db0d354116767adc to your computer and use it in GitHub Desktop.
Save LewisW/eb50db0d354116767adc to your computer and use it in GitHub Desktop.
Twig macro for mapping a mime type to a font-awesome icon.
{% import 'Path:To:filemacros.html.twig' as file %}
<span class="fa {{ file.icon(attachment.file.mimeType) }}"> </span>
{% macro icon(mimeType) %}
{% spaceless %}
{% if mimeType == 'application/pdf' %}
fa-file-pdf-o
{% elseif mimeType in [
'application/msword',
'application/rtf',
'application/x-rtf',
'text/richtext'
] %}
fa-file-word-o
{% elseif mimeType in [
'application/mspowerpoint',
'application/vnd.ms-powerpoint',
'application/x-mspowerpoint'
] %}
fa-file-powerpoint-o
{% elseif mimeType in [
'application/excel',
'application/x-excel',
'application/x-msexcel',
'application/vnd.ms-excel',
'text/csv',
'text/tab-separated-values'
] %}
fa-file-excel-o
{% elseif mimeType in [
'application/x-cpio',
'application/x-shar',
'application/x-tar',
'application/gnutar',
'application/x-bzip',
'application/x-bzip2',
'application/x-gzip',
'multipart/x-gzip',
'application/x-lzip',
'application/x-lzma',
'application/x-lzop',
'application/x-xz',
'application/x-compress',
'application/x-7z-compressed',
'application/x-ace-compressed',
'application/vnd.android.package-archive',
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
'application/x-zip'
] %}
fa-file-archive-o
{% elseif 'image/' in mimeType %}
fa-file-image-o
{% elseif 'audio/' in mimeType %}
fa-file-audio-o
{% elseif 'video/' in mimeType %}
fa-file-video-o
{% elseif 'text/' in mimeType %}
fa-file-text-o
{% else %}
fa-file-o
{% endif %}
{% endspaceless %}
{% endmacro %}
{% macro bytesToSize(bytes) %}
{% spaceless %}
{% set kilobyte = 1024 %}
{% set megabyte = kilobyte * 1024 %}
{% set gigabyte = megabyte * 1024 %}
{% set terabyte = gigabyte * 1024 %}
{% if bytes < kilobyte %}
{{ bytes ~ ' B' }}
{% elseif bytes < megabyte %}
{{ (bytes / kilobyte)|number_format(2, '.') ~ ' KB' }}
{% elseif bytes < gigabyte %}
{{ (bytes / megabyte)|number_format(2, '.') ~ ' MB' }}
{% elseif bytes < terabyte %}
{{ (bytes / gigabyte)|number_format(2, '.') ~ ' GB' }}
{% else %}
{{ (bytes / terabyte)|number_format(2, '.') ~ ' TB' }}
{% endif %}
{% endspaceless %}
{% endmacro %}
@mherchel
Copy link

mherchel commented Apr 5, 2024

This just saved me like hours of work. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment