Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active September 9, 2019 05:55
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/8033606b6e8339d1f414698b47ee70c5 to your computer and use it in GitHub Desktop.
Save piotrpog/8033606b6e8339d1f414698b47ee70c5 to your computer and use it in GitHub Desktop.
Macro returning elapsed time in human-readable format. More info: http://craftsnippets.com/articles/working-with-dates-in-craft-cms-templates
{%- macro timeAgo(date, additionalAttributes) -%}
{# v1 #}
{% if date is defined %}
{# settings #}
{% set format = 'medium' %}
{% set locale = currentSite.language %}
{# logic #}
{% set formatter = create({ class: 'craft\\i18n\\Formatter', locale: locale }) %}
{% set attributes = {
text: formatter.asRelativeTime(date),
datetime: date|date('yy-m-d'),
title: date|date(format),
} %}
{% if additionalAttributes is defined and additionalAttributes is not iterable %}
{% set attributes = attributes|merge({class: additionalAttributes}) %}
{% elseif additionalAttributes is iterable %}
{% set attributes = attributes|merge(additionalAttributes) %}
{% endif %}
{{tag('time',attributes)}}
{% endif %}
{%- endmacro -%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment