Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active July 11, 2019 19:07
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/8038cc521bc324756d1f1e9b6821335c to your computer and use it in GitHub Desktop.
Save piotrpog/8038cc521bc324756d1f1e9b6821335c to your computer and use it in GitHub Desktop.
Macro truncating text by the number of words. More info: http://craftsnippets.com/articles/truncating-text-with-twig-macros-in-craft-cms
{# v1 #}
{% macro truncateWords(text, length, suffix) %}
{% spaceless %}
{# settings #}
{% set defaultSuffix = '...' %}
{# logic #}
{% if text and length %}
{% set suffix = suffix|default(defaultSuffix) %}
{% set text = text|striptags %}
{% set text = text|replace('/\\n/', '\n ') %}
{% set array = text|split(' ') %}
{% set arrayTruncated = array|slice(0, length) %}
{% set string = arrayTruncated|join(' ') %}
{% if array|length > length %}
{% set string = string ~ suffix %}
{% endif %}
{% set string = string|replace('/\\n\\s/', '\n') %}
{{ string }}
{% endif %}
{% endspaceless %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment