Great news that Drupal 8 WYSIWYG editor now is ready for image captions, but actually I need image captions showing with images configured by Manage Display of content type.

The problem is that none of the modules like Image Caption are not D8 ready by now.

The right way to implement this seems to be by creating a custom Field Formatter. Actually there is a fantastic article showing how to implement this as a module. But something changed in Drupal API and using this code shows a blank Manage Display page without any error reporting.

Anybody has a solution for adding image captions to Drupal 8?

Comments

jonodunnett’s picture

Using module from the repo linked to from https://www.sitepoint.com/community/t/creating-custom-field-formatters-i...
Wasn't working initially but by changing line 29 of imagecaption.php from
public function viewElements(FieldItemListInterface $items) {
to
public function viewElements(FieldItemListInterface $items, $langcode) {

I could install the module OK and select the formatter, and the new formatter was used, but the caption was not showing up.

Then changed line 21 of image_caption_title.module from
$vars['caption'] = SafeMarkup::checkPlain($vars['item']->get('title')->getValue());
to
$vars['caption'] = SafeMarkup::checkPlain($vars['item']->get('alt')->getValue());

and captions now show :)

ali_b’s picture

Fatal error: Cannot use Drupal\Component\Utility\String as String because 'String' is a special class name

ihagen’s picture

{#
/**
 * @file
 * Theme override to display a formatted image field.
 *
 * Available variables:
 * - image: A collection of image data.
 * - image_style: An optional image style.
 * - url: An optional URL the image can be linked to.
 *
 * @see template_preprocess_image_formatter()
 */
#}

{% set titles = image['#title']|split('||', 2) %}
{% set caption = titles['0'] %}
{% set image = image|merge({'#title': titles['1'] }) %}

{% if caption %}
<figure role="group">
{% endif %}
{% if url %}
  <a href="{{ url }}">{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}
{% if caption %}
<figcaption>{{ caption }}</figcaption>
</figure>
{% endif %}
diamondsea’s picture

This is a simple solution that works well. 

To use this, enable the TITLE field on your Image field and paste the above code file into your theme as /themes/your_theme/templates/field/image-formatter.html.twig.

MaskyS’s picture

We now have a working D8 version of Image Caption here: https://www.drupal.org/sandbox/maskys/2933889

This is still in development and should not be used in prod.

renguer0’s picture

How do we enable the image caption on WYSIWYG editor on D8?

I'm using the TWIG template that hihagen posted here.