Last active
July 11, 2019 19:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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