Question

I want to control html view using php. Simple way is to add if condition e.g.

<?php if(condition)
 echo '<div>something what I want to show</div>';
?>

but I want to find something like in JavaEE where I can control rendering html element using render attribute.

I'm looking for something like this:

<div render="Class::methodThatWillCheckConditions()"></div>

Is it possible to do something like this is PHP?

Was it helpful?

Solution

Many PHP frameworks like Symfony 2 have integrated methods for generating HTML.

You can also write your own functions and call them whenever needed.

You'll also be able to call Class::methodThatWillCheckConditions() then, but as far as I am concerned, you still have to echo it out.

You may find some other ways here: How can I echo HTML in PHP?

I really like the method of doing it in between PHP tags - this way your IDE will keep your HMTL syntax highlighted properly. Alternate syntax improves readability:

<?php if(condition) : ?>
    <div>Hello, World!</div>
<?php endif; ?>

I hated this syntax when I started, but it's great compared to curly brackets in a big html document. Imagine you have the closing bracket 150 lines later, } won't tell you what's closing. endif tells you exactly a if-statement is closing.

So I'd recommend you to write functions for this where you can pass parameters and modify them to your needs, or even write it plain like in my example above.

PS: Don't use short tags!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top