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

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

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

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!


Added hook_page_attachments(_alter)() and removed hook_page_build/alter()

function hook_page_attachments

current_path() is replaced by the <current> route

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

No comments:

Post a Comment