PHP: How to hide / show pieces of HTML

I hope someone can help beginners with this question. I just came from an ASP.Net environment where it was easy to hide or show pieces of HTML. For example: Different stages of a form, depending on what the user has entered.

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

I am sure there should be a better way to hide or show pieces of HTML without having to include the echo operator, but I cannot find any online documentation that explains how to do this.

Thanks for any tips, hints or links to good PHP resources for this level of problems.

+6
source share
4 answers

Given PHP as an embedded language, you should use special language forms for "templates" to get better readability.

Instead of using an echo, you can simply write HTML outside of the <?php ?> Tags (never use <? ?> , Which can be misleading).

It is also suggested to use if () : instead of if () { , for example:

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

Literature:

+15
source

You do not need to put HTML in an echo statement. Think of the fact that HTML is implicitly echo ed. So, to conditionally display an HTML fragment, you would look for the following construction:

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

Thus, an HTML string literal that exists outside of PHP tags is simply implicitly delivered to the page, but you can wrap the logic around it to control it. In the above text, the div and its contents are included in the scope of the if , and therefore a piece of HTML (even if it is outside of the PHP tags) is supplied only if the condition in the PHP code is true .

+3
source

Try the following:

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

You can use PHP tags, for example, wrapped around HTML, and based on conditional HTML will either display or not.

+2
source

That should work too. For instance. to hide / show the table tag.

 <table <?php echo (condition == true)?'visible':'hidden'; ?> ></table> 
0
source

Source: https://habr.com/ru/post/885923/


All Articles