Skip to content

Instantly share code, notes, and snippets.

@beryllium
Created March 11, 2018 01:23
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 beryllium/6ac7f805cba51b7125edf38e36bc3486 to your computer and use it in GitHub Desktop.
Save beryllium/6ac7f805cba51b7125edf38e36bc3486 to your computer and use it in GitHub Desktop.
Time-Ago Twig Macro
{# Based on this StackOverflow example: https://stackoverflow.com/a/26311354/1272059 #}
{% macro time_ago(timestamp) %}
{% set lapse = date().getTimestamp() - timestamp %}
{% set units = {
'year': 31536000,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1,
}
%}
<span class="friendlyDate">
{% set foundVal = false %}
{% for val,unit in units %}
{% if not foundVal and lapse >= unit %}
{% set foundVal = true %}
{% if val == 'second' %}
a few seconds ago
{% else %}
{% set numberOfUnits = lapse // unit %}
{% if numberOfUnits > 1 %}
{{ numberOfUnits }} {{ val }}s ago
{% else %}
a {{ val }} ago
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
</span>
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment