M
M
Marty McFly2020-04-22 09:18:38
PHP
Marty McFly, 2020-04-22 09:18:38

What are the best practices for mixing layout with php?

Hello!
Are there any best practices when, let's say, php is used as a "template engine" in the layout?
I'm trying to clean up the source code of the page, the indentation is a mess all over the place.

I realized that you should not use indents for layout inside php structures, since the server returns a page where all php inserts "disappear", but the indents remain.

That is, you need to write not like this:

<div class="c-tab__nav" role="tablist" aria-label="<?php echo lang('tabsLabel'); ?>">
    <?php foreach ($data['thisUserFields'] as $key => $value): ?>
        <?php if ($value['type'] === 'textarea' && !empty($value['value'])): ?>
            <button class="js-open-tab c-tab__link"
                    role="tab"
                    id="c-tab-btn-<?php echo $key ?>"
                    aria-selected="false"
                    tabindex="0"
                    aria-controls="c-tab__tab<?php echo $key ?>">
                <?php echo $value['name'] ?>
            </button>
        <?php endif; ?>
    <?php endforeach; ?>
</div>

and like this:
<div class="c-tab__nav" role="tablist" aria-label="<?php echo lang('tabsLabel'); ?>">
    <?php foreach ($data['thisUserFields'] as $key => $value): ?>
        <?php if ($value['type'] === 'textarea' && !empty($value['value'])): ?>
    <button class="js-open-tab c-tab__link"
            role="tab"
            id="c-tab-btn-<?php echo $key ?>"
            aria-selected="false"
            tabindex="0"
            aria-controls="c-tab__tab<?php echo $key ?>">
        <?php echo $value['name'] ?>
    </button>
        <?php endif; ?>
    <?php endforeach; ?>
</div>


This visually spoils the structure, especially when, with a large nesting, php starts moving to the right, and the layout still has to be pressed to the left edge.

How do you do it?
Let's just without "there is no php in my layout" and "there is no layout in my php", "Use a template engine" and so on.
Is there a specific case, how best to act in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2020-04-22
@alex_shevch

The browser renders the page based on the html generated by the server, the indents in the template do not matter to it. Indentation when mixing php and html should be done for the benefit of readability.
On a note - in a template it is necessary to use an alternative syntax of managing structures . And replace <?php echo with <?= .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question