Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active Sep 9, 2019
Embed
What would you like to do?
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