Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to hide/display chunks of HTML

Tags:

html

php

I'm hoping someone can help with this very newbie question. I've just come from an ASP.Net environment where it was easy to hide or show chunks of HTML. For example: Different stages of a form, depending on what the user had entered.

Hiding or showing <div>/<asp:Panel>s was very simple, but in PHP all I can think to do is put my HTML into an echo statement. This makes the HTML very difficult to read, difficult to maintain and the whole file looks rather messy.

I'm positive there must be a better way of hiding or showing chunks of HTML without having to involve an echo statement, but I can't find any online documentation that explains how.

Thanks for any tips, advice or links to good PHP resources for this level of problem.

like image 337
Chuck Le Butt Avatar asked Apr 14 '11 16:04

Chuck Le Butt


3 Answers

Considering PHP as an embedded language you should, in order to get better readability, use the specific language forms for the "templating".

Instead of using echo you could just write the HTML outside the <?php ?> tags (never use <? ?> which could be misleading).

Also it is suggested to use if () : instead of if () {, for example:

<body>
    <?php if (true) : ?>
        <p>It is true</p>
    <?php endif; ?>
</body>

References:

  • Alternative syntax
like image 69
Shoe Avatar answered Nov 19 '22 07:11

Shoe


You don't need to put the HTML into an echo statement. Think of the HTML as implicitly being echoed. So, for conditionally showing a chunk of HTML, you'd be looking for a construct like this:

<?php
    if (condition == true) {
?>
    <div>
        <p>Some content</p>
    </div>
<?php
    }
?>

So the HTML string literal that exists outside of the PHP tags is just implicitly delivered to the page, but you can wrap logic around it to drive it. In the above, the div and its contents are all within the scope of the if statement, and so that chunk of HTML (even though it's outside of the PHP tags) is only delivered if the condition in the PHP code is true.

like image 42
David Avatar answered Nov 19 '22 06:11

David


Try this:

<?php if ($var == true) { ?>
    <table>...</table>
<?php } ?>

You can use PHP tags like wrapped around HTML and based on the conditional the HTML will either be rendered or it won't.

like image 3
Nik Avatar answered Nov 19 '22 05:11

Nik