Skip to content

Instantly share code, notes, and snippets.

@mikestecker
Forked from piotrpog/Twig truncate macro
Created January 3, 2019 23:29
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 mikestecker/09b75bb217f3293dd615c55cbb0c71de to your computer and use it in GitHub Desktop.
Save mikestecker/09b75bb217f3293dd615c55cbb0c71de to your computer and use it in GitHub Desktop.
{% macro truncate(text, limit, append) %}
{# settings #}
{% set suffix = append|default('...') %}
{% set punctuation = ['.',',','-',':',';'] %}
{# logic #}
{% set array = text|split(' ') %}
{% set arrayTruncated = array|slice(0, limit) %}
{% set string = arrayTruncated|join(' ') %}
{% if limit and array|length > limit %}
{% for mark in punctuation %}
{% set string = string|trim(mark) %}
{% endfor %}
{% set string = string ~ suffix %}
{% endif %}
{{ string }}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment