How can I use conditional logic to not display a <div> in page.tpl.php based on node id?

drupal.stackexchange https://drupal.stackexchange.com/questions/802

  •  16-10-2019
  •  | 
  •  

Question

I'm using a theme that has regions not supported by Panels' "Disable Drupal blocks/regions" settings. I've tried to remove the using an if statement in PHP, but either my PHP syntax is wrong or I'm not using the correct Drupal variables. Right now the section looks like this:

<?php
    if ($node->nid != 51) {
        echo '<div id="left">';
            { if ($left) { print $left;}
        echo '</div>';
 ?>

I have a feeling I'm not nesting the second if statement correctly in PHP though.

Was it helpful?

Solution

If you're trying to hide the left sidebar when viewing node 51, this is not the right way to do it. Edit the block visibility settings for the blocks in the left sidebar so they are hidden when the path is 'node/51'. Then in your template you can do this:

<?php
  if ($left) {
    print '<div id="left">' . $left . '</div>';
  }
?>

This will hide the entire div#left when there are no blocks in the left sidebar.

OTHER TIPS

I think that altering the visibility settings for all the blocks shown in the left sidebar is the correct way to hide the left sidebar.
If, for any reason, you need to hide the left sidebar from code (for example, because you need to hide the left sidebar in specific conditions that are not the URL of the currently show page), then what you can do is implementing hook_preprocess_page(), which is invoked before the page template is rendered. That hook is allowed to alter any variable that is passed to the page template.

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 51) {
    // The left sidebar will not be shown.
    $variables['left'] = '';
    // …
  }
  // …
}

The hook can check more complex conditions are verified, including verifying that some node fields have specific values, which is not possible when changing the block visibility settings, if not writing PHP code that is then passed to eval() from the block module (in such cases, it is better to put that code into a custom module).

The reason you are getting an syntax error is that the code contains a curly bracket that doesn't match a closing bracket, and there is a missing closing bracket.

if ($node->nid != 51) {
  echo '<div id="left">';
    /* This bracket is extra. -> */ { if ($left) { print $left;}
  echo '</div>';
} /* <- This bracket is missing in the code you reported. */
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top