ckeditor icon indicating copy to clipboard operation
ckeditor copied to clipboard

Twig length filter no longer returns the length of the field contents

Open martyspain opened this issue 1 year ago • 2 comments

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

  1. Create a CKEditor field using plugin v4.x
  2. Add text to this field (no nested entries, just HTML)
  3. Use the length Twig filter on the field's value
  4. Observe the returned value of 1 instead 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

martyspain avatar Jul 04 '24 13:07 martyspain

+1

olsp avatar Jul 17 '24 19:07 olsp

In the meantime, I found a workaround: description | split('') | length

olsp avatar Jul 17 '24 19:07 olsp

You can get the length of the parsed markup like so:

{{ entry.description.parsedContent|length }}

brandonkelly avatar Sep 09 '24 15:09 brandonkelly