Beget views dynamics, according to certain parameters, is a challenge in any language.
There are basically three main approaches to dealing with this:
Scripts
The approach of mixing scripts with HTML is the most efficient, but can easily lead to code difficult to understand, maintain and error-prone.
Template Engines
Use a mechanism of templates helps separate logic from presentation. The side effect is performance, since the templates need to be interpreted to generate the output.
Some mechanisms allow the "compilation" of templates to solve the problem of performance, but this will require further care in implementing.
Particularly I like the approach based on templates.
Components
Some frameworks generate views through components, which are actually a collection of objects that encapsulate the generated HTML.
In PHP this is not as common as in Java, for example, but if I remember well Yii works this way.
The advantage is that there is a degree of code reuse, but due to the great abstraction and complexity you can easily lose control of what you’re doing, in addition to making tasks that would once be trivial into something that depends on a relatively deep knowledge of the framework.
Considerations
There is no problem in using some ifs
or loops in the code, as long as you can separate it from the logic of the system.
A very simple example of how to use the PHP language itself as a type of template engine, thus avoiding the large amount of classes included when using frameworks, can be seen in some templates of Wordpress. Example:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!-- do stuff ... -->
<?php endwhile; ?>
<?php endif; ?>