Created
March 11, 2018 01:23
-
-
Save beryllium/6ac7f805cba51b7125edf38e36bc3486 to your computer and use it in GitHub Desktop.
Time-Ago Twig Macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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