简体   繁体   中英

Hide header if node body is empty - Drupal php snippet help

I've made a content type for links, I'm trying to make a link directory. People only have to submit the link, description is voluntary. If no description is entered, I want the header that says "description" to disappear. The description field is the node body. Right now my snippet looks like this

<?php if (!empty($node->body)) {?> 
<div class="field field-type-link field-field-link-archive">
<h3>Description</h3>
<?php print $node->content['body']['#value'] ?></div>
<?php }?>

I expect this to check if node body is not empty, and if it isn't it'll print what's there. The problem is that the Description header is still printed out even if the node body is empty. Can anyone see what's wrong?

$node->body is whole node content with links, author info, post date etc.
You almost got it, see:

<?php if (!empty($node->content['body']['#value'])) {?> 
<div class="field field-type-link field-field-link-archive">
<h3>Description</h3>
<?php print $node->content['body']['#value'] ?></div>
<?php }?>

Also some wysiwyg-s modules automatically adds tags like p. Check it...

In Drupal 7, this will also work:

<?php if(!empty($content['body'])) { ?>
 <div class="field field-type-link field-field-link-archive">
   <h3>Description</h3>
   <?php print render($content['body']); ?>
 </div>
<?php }?>

$node->body probably isn't empty

These are things that php considers to be empty

"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

do a var_dump on it to test it

And phps shorthand syntax was made for things like that. you shoudl use it it's much easier to read

<?php if(): ?>
// do stuff
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM