Twig length filter no longer returns the length of the field contents
Description
In versions of the CKEditor plugin prior to 4.x, the length Twig filter could be used to return the length of the raw text in the field.
{# CKEditor field using plugin v3.x #}
{% set description = entry.description %}
{% if description|length > 370 %}
{# Length is too long so truncate CKEditor field text #}
{% set initialDescription = description|striptags|truncate(360, '...') %}
{% endif %}
In 4.x, this no longer works, presumably due to internal changes to support nested entries. The length filter returns 1.
{# CKEditor field using plugin v4.x #}
{% set description = entry.description %}
{% if description|length > 370 %}
{# We never reach this point because the length filter returns 1, not the length of the raw text #}
{% set initialDescription = description|striptags|truncate(360, '...') %}
{% endif %}
I don't believe there were any migration notes added for this change, so perhaps I've been using the length filter incorrectly all this time with Redactor/CKEditor fields! Either way, this doesn't work any more.
Having read through the docs for 4.x, there's a workaround for this but it's quite verbose and a bit fragile:
{# Fetch markup chunk from CKEditor field using plugin v4.x #}
{% set description = entry.description|filter(chunk => chunk.type == 'markup')|first %}
{% if description|length > 370 %}
{# The length filter now works as expected #}
{% set initialDescription = description|striptags|truncate(360, '...') %}
{% endif %}
Steps to reproduce
- Create a CKEditor field using plugin v4.x
- Add text to this field (no nested entries, just HTML)
- Use the
lengthTwig filter on the field's value - Observe the returned value of
1instead of v3.x behaviour which would return the length of the raw text value
Additional info
- Craft version: 5.2.5
- PHP version: 8.2
- Database driver & version: MySQL 8.0
- Plugins & versions: CKEditor 4.1.0
+1
In the meantime, I found a workaround: description | split('') | length
You can get the length of the parsed markup like so:
{{ entry.description.parsedContent|length }}