Jan 1, 2015

Beta 4: hook_page_build() has been removed, as well as function current_path()

hook_page_build() has been removed and replaced with several other hooks. In our case, we used the new hook_page_attachments() since a dynamically generated piece of javascript is being attached to selected pages.

So instead of

  function optimizely_page_build(&$page) { .... }

in the D8 version it is

  function optimizely_page_attachments(array &$page) { .... }

The body of the hook function remained largely the same, but there were some changes as described below.



Function current_path() has been removed in favor of using the built-in route <current>. For example, in place of

  $curr_path = current_path();

I did this,

  $url = \Drupal\Core\Url::fromRoute('<current>');
  $curr_path = $url->toString();



N.B. The value of $curr_path in this example code contains a leading slash character. Although I'm not certain, from the reading I've done so far, it seems this is considered the standard for internal paths within D8.

Unfortunately, this is at odds with how paths are specified by users of the D7 version of the module and causes path matching to fail.

I decided to fix this in our code by stripping off such a leading slash. This preserves compatibility with D7 data, but possibly violates D8 conventions.



In D7, pulling in javascript from an external source can be done with something like this.

  $page['#attached']['js'][] = array(
    'type' => 'external',
    'data' => $js_snippet,
  );

Attaching javascript directly in this way is no longer allowed.

For static js and css, you can use libraries as described in the posting
http://optimizely-to-drupal-8.blogspot.com/2014/12/beta-3-beta-4-use-libraries-not.html

For the dynamically generated javscript needed for the module, here's what I did.

  $page['#attached']['html_head'][] = array(
    array(
      '#tag' => 'script',
      '#attributes' => array(
        'type' => 'text/javascript',
        'src' => $js_snippet,
      ),
      '#value' => '',
    ),
    'optimizely-snippet',
  );

That last array element 'optimizely-snippet' is not actually used in this module. I include it as example of "a key, to make it possible to recognize this HTML <HEAD> element when altering".

Happy 2015!



Sources:

Added hook_page_attachments(_alter)() and removed hook_page_build/alter()
https://www.drupal.org/node/2357755

function hook_page_attachments
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_page_attachments/8.0.x

current_path() is replaced by the <current> route
https://www.drupal.org/node/2382211

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
https://www.drupal.org/node/2274843

No comments:

Post a Comment