d8-contrib-modules / views_slideshow

D8 port of Views Slideshow, owned by Vincent
0 stars 1 forks source link

Access drupalSettings from preprocess function #1

Open vbouchet31 opened 9 years ago

vbouchet31 commented 9 years ago

In template_preprocess_views_slideshow_cycle_main_frame() (views_slideshow_cycle/views_slideshow_cycle.theme.inc), we need to check all previously drupal js settings set to be sure it is not here yet. If it is already here, we should increment a counter to be sure the id is unique.

In D7, it was achieved by using drupal_add_js() without any parameters to retrieve all js settings:

  $slideshow_count = 1;
  $current_settings = drupal_add_js();
  foreach ($current_settings['settings']['data'] AS $current_setting) {
    if (isset($current_setting['viewsSlideshowCycle'])) {
      $current_keys = array_keys($current_setting['viewsSlideshowCycle']);
      if (stristr($current_keys[0], '#views_slideshow_cycle_main_' . $vss_id)) {
        $slideshow_count++;
      }
    }
  }

  if ($slideshow_count > 1) {
    $vss_id .= '-' . $slideshow_count;
    $settings['vss_id'] = $vss_id;
  }

...

  $vars['#attached']['drupalSettings']['viewsSlideshowCycle']['#views_slideshow_cycle_main_' . $vss_id] = $settings;

We should find the proper way to access drupalSettings in D8.

For now I used a global variable to store processed slidehows:

  $slideshow_count = 1;
  global $processedCycles;
  if (is_array($processedCycles)) {
    foreach ($processedCycles as $processedCycle) {
      if (stristr($processedCycle, '#views_slideshow_cycle_main_' . $vss_id)) {
        $slideshow_count++;
      }
    }
  }

  if ($slideshow_count > 1) {
    $vss_id .= '-' . $slideshow_count;
    $settings['vss_id'] = $vss_id;
  }

...

  $vars['#attached']['drupalSettings']['viewsSlideshowCycle']['#views_slideshow_cycle_main_' . $vss_id] = $settings;

  $processedCycles['#views_slideshow_cycle_main_' . $vss_id] = '#views_slideshow_cycle_main_' . $vss_id;
damontgomery commented 9 years ago

Could you provide an alternative way of providing a unique ID? It doesn't have to be an integer than increments. Maybe https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Uuid!UuidInterface.php/function/UuidInterface%3A%3Agenerate/8 ?

A better method would be to pass the settings as a javascript data- attribute and not try to have such a tight relationship between the backend and frontend code. I imagine rewriting the JS is too much for now though.

vbouchet31 commented 9 years ago

Thank you for your suggestion. I need to do further investigation as this vss_id (probably ViewsSlideShow_ID) is used in many place (not even generated by views_slideshow_cycle initially) and may be used for theming in some places.