[5.x] Make photoswipe library attachable in theme ({ attach_photoswipe() })

Created on 27 June 2018, over 6 years ago
Updated 8 August 2023, over 1 year ago

Before implementing this, we should discuss if it wouldn't make sense to switch to Photoswipe v5 first, see [5.x] PhotoSwipe 5 Branch Fixed
As that change will have large implications on this issue.

+ PP until this is fixed in core: #2982040: Provide a hook to act on attaching libraries

Context:

A certain page requires photoswipe. For example for a paragraph template file which contains an image that should be zoomable but doesn't use typical field formatter for that.

Problem:

Currently that integration can only be done by coding PHP using #attached e.g. the ->attach() function in photoswipe
OR
Using the global option to load photoswipe on non-admin pages

Both is bad for themers with the same arguments why

{# In a Twig template we attach the library. #}
{{ attach_library('bartik/messages') }}

was developed. (See https://www.drupal.org/node/2456753 )

The attach() function in src/PhotoswipeAssetsManager.php has the problem that it adds settings and within even provides the pswp container. {{ attach_library }} isn't capable of that so that using

{{ attach_library('photoswipe/photoswipe') }}
{{ attach_library('photoswipe/photoswipe.init') }}

wouldn't work correctly without further changes in the module itself.

  public function attach(array &$element) {
    // We only need to load only once per pace.
    if (!$this->attached) {
      // Add the library of Photoswipe assets.
      $element['#attached']['library'][] = 'photoswipe/photoswipe';
      // Load initialization file.
      $element['#attached']['library'][] = 'photoswipe/photoswipe.init';

      // Add photoswipe js settings.
      $element['#attached']['drupalSettings']['photoswipe']['options'] = $this->config->get('options');

      // Add photoswipe container with class="pswp".
      $template = ["#theme" => 'photoswipe_container'];
      $element['#attached']['drupalSettings']['photoswipe']['container'] = $this->renderer->renderPlain($template);

      $this->attached = TRUE;
    }
  }

Proposed solution

Remove the "drupalSettings" part from the attach() function and move it into photoswipe_page_attachments to make the options available globally.
Keep the library part of attach() to load both libraries as before for normal use cases
Now you can also flexibly use

{{ attach_library('photoswipe/photoswipe') }}
{{ attach_library('photoswipe/photoswipe.init') }}

in the theme without coding PHP and require photoswipe whenever you need it.

Feature request
Status

Fixed

Version

5.0

Component

Code

Created by

🇩🇪Germany Anybody Porta Westfalica

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024