0

I've created my own block which calls a hook_theme implementation which then prepares some data and then renders myblock.tpl.php

All of the above is working fine but my module does have some required assets, specifically some css & js files, currently I was doing drupal_add_css/js in my hook_block($delta = 'view') but I've discovered that both the hook_block and hook_theme do not get called when the Admin > Config > Performance - Enable Block Cache has been turned on.

Obviously when I clear the cache the first load of a page (with my block included) loads all assets properly, but anon-users etc do not see any of my assets.

How should I be including these assets in a way that would withstand caching and only add assets on a page which includes my block?

Thanks!

1

Modules can report how Drupal should cache the output of a module, through the use of a set of constants.

The constants should be used as in the following example of hook_block():

function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Mymodule block #1 shows ...'), 
      'weight' => 0, 
      'status' => 1, 
      'region' => 'left',
    );
    // BLOCK_CACHE_PER_ROLE will be assumed for block 0.

    $blocks[1] = array(
      'info' => t('Mymodule block #2 describes ...'), 
      'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE,
    );

    return $blocks;
  }
  // …
}

The constants that can be used are:

  • BLOCK_NO_CACHE: The block should not be cached.
  • BLOCK_CACHE_GLOBAL: The block is the same for every user, in every page it is shown.
  • BLOCK_CACHE_PER_ROLE: The block could change basing on the roles the user who is watching the page has.
  • BLOCK_CACHE_PER_USER: The block could change basing on the user who is watching the page.
  • BLOCK_CACHE_PER_PAGE: The block could change basing on the page being viewed.

You could use some of the constants together; for example, if the block changes basing on the page, and the user who is watching the page, you can use BLOCK_CACHE_PER_PAGE|BLOCK_CACHE_PER_USER.

In Drupal 7, those constants have been renamed, and a new constant is added; this is the list of the constants used in Drupal 7:

  • DRUPAL_NO_CACHE
  • DRUPAL_CACHE_GLOBAL
  • DRUPAL_CACHE_PER_ROLE
  • DRUPAL_CACHE_PER_USER
  • DRUPAL_CACHE_PER_PAGE
  • DRUPAL_CACHE_CUSTOM

The last constant is used to report to Drupal 7 that the module uses its own cache. For Drupal it has the same effect of using DRUPAL_NO_CACHE.

  • Ahh... Ok. I presume that the various caching levels will then cache the various parts of the request - I can then put my drupal_add_js where it's applicable! Thanks! – electblake Aug 18 '11 at 0:29

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.