Help with conditional

Hi there,
I’m building a template for a book review, and sometimes I don’t have all the field.

So on top of my template I have sometingh like:

<?php
$Year=$page->Year();
$Author=$page->Author();
$Title=$page->Title();
$Publisher=$page->Publisher();
$Number_of_pages=$page->Number_of_pages();
$Photography=$page->Photography();
$Author_Url=$page->Author_Url();
$Curator=$page->Curator();
$Bio=$page->Bio();
$Book_Text=$page->Book_Text();
$Book_Language=$page->Book_Language();
$ISBN=$page->ISBN();
$Size=$page->Size();
$Translator=$page->Translator();
$Interview=$page->Interview()->kirbytext();
?>

Then inside the template I’d like to print only the field that are not empty. I’ve tried somethig like:

		<? if ($Book_Text->isNotEmpty()) {
			echo '<dt>';
			echo l::get('book_text');
			echo '</dt>';
			echo '<dd>';
			echo $Book_Text;
			echo '</dd>';
		}
		?>

It’s work, but… Is there a better way to write the same in a compact way?

Thanks!

EDIT: The same for the following; is there a way to write it in a more compact/readable way?

	<?php if($Author_Url->isNotEmpty()){ ?>	
	<p>
		<a href="http://<? echo $Author_Url ?>"><? echo $Author_Url ?></a>
	</p>
	<?php } ?>

First of all I think you shouldn’t define all fields at the top of the template. It’s just very hard to read and can also lead to bugs that are hard to spot if you have a typo somewhere.

We’d recommend the following syntax:

<?php if($page->book_text()->isNotEmpty()): ?>
  <dt><?= l::get('book_text') ?></dt>
  <dd><?= $page->book_text() ?></dd>
<?php endif?>

As you can see I have mainly changed three things:

  • Used $page->book_text() directly. The performance is the same, but it’s easier to read.
  • Replaced <? with <?php. Using the short open tag is not recommended.
  • The HTML tags are written directly and not printed by PHP echo commands. Again much easier to read.

Regarding your other example:

<?php if($page->author_url()->isNotEmpty()): ?>
  <p>
    <a href="http://<?= $page->author_url() ?>"><?= $page->author_url() ?></a>
  </p>
<?php endif ?>
1 Like

Thanks! This help me a lot!

just to clarify. <?= is not a shorttag. its available since php 5 and just short for <?php echo.

Thanks for clarifying!
After my post, I’ve investigated the answer and found several interesting thing like the one you said. I’m a designer, not a developer and sometimes is not easy to use the right keywords to search :slight_smile:
Anyway, for developers dummies like me, everything is well explained in this recipe: Kirby PHP templates :slight_smile:

That’s true. What I meant was the <? tag (without the equal sign). :slight_smile: