3

Use case:

I have a custom block:

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "my",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $build = array(
      '#markup' => 'SOME WEIRD ADS HTML HERE'
    );

    SOME_COOL_STUFF_TO_ADD_INLINE_JAVASCRIPT_TO_THE_CLOSING_BODY_TAG

    return $build;
  }
}

Is there a way to add inline javascript to the end of the page just when this block is rendered anywhere (in theme or panel page)?

  • The answer is actually no, not really. You can ad it right there as inline within the #markup (you might need to create a safe string with Markup::create). But what you can do for example is combine a library with drupalSettings to instrumentalize it. And then loop over ad positions in a drupal behavior based on the settings. That's what we're doing. – Berdir Aug 10 '16 at 20:14
2

You just use the following code.

$build = [
  '#markup' => 'SOME WEIRD ADS HTML HERE',
  '#attached' => [
    'library' => ['mymodule/mylibrary'],
  ],
];

Follow Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module to learn how to define a library for Drupal 8, and keep in mind that, by default, JavaScript files are added to the footer, as explained in LibraryDiscoveryParser::parseLibraryInfo().

By default, JavaScript files are included in the footer.

Also, #markup is filtered out, as explained in Render API overview.

#markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (For example, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.