Skip to content

Instantly share code, notes, and snippets.

@Cartroo
Created July 12, 2023 09:10
Show Gist options
  • Save Cartroo/25096e66362e79e165209e13a3f8fad9 to your computer and use it in GitHub Desktop.
Save Cartroo/25096e66362e79e165209e13a3f8fad9 to your computer and use it in GitHub Desktop.
Useful Jinja macros
{% macro plural(num, unit) -%}
{{ num }} {% if num == 1 %}{{ unit }}{% else %}{{ unit }}s{% endif -%}
{%- endmacro %}
{% macro ordinal(number) -%}
{%- if number % 100 > 3 and number % 100 < 21 -%}{{ number }}th
{%- elif number % 10 == 1 -%}{{ number }}st
{%- elif number % 10 == 2 -%}{{ number }}nd
{%- elif number % 10 == 3 -%}{{ number }}rd
{%- else -%}{{ number }}th{%- endif -%}
{%- endmacro %}
{% macro readTime(wordCount,wpm=200) -%}
{% if (wordCount/wpm)>=1 %}
{{ plural((wordCount//wpm), "minute") }}
{% else %}
{{ plural((wordCount//wpm)*60, "second") }}
{% endif %}
{%- endmacro %}
{% macro age(time) -%}
{%- set now = time.now(tz=time.tzinfo) -%}
{%- set offset = now - time -%}
{%- if offset.days > 600 -%}
{{ plural(now.year - time.year, "year") }}
{%- elif offset.days > 69 -%}
{{ plural((now.year - time.year) * 12 + now.month - time.month, "month") }}
{%- elif offset.days > 6 -%}
{{ plural(offset.days // 7, "week") }}
{%- elif offset.days > 0 -%}
{{ plural(offset.days, "day") }}
{%- elif offset.seconds > 3600 -%}
{{ plural(offset.seconds // 3600, "hour") }}
{%- elif offset.seconds > 3600 -%}
{{ plural(offset.seconds // 60, "minute") }}
{%- else -%}
{{ plural(offset.seconds, "second") }}
{%- endif -%}
{%- endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment