Search code examples
phpdryclass-attributes

HTML attributes and PHP - where to draw the line between conflicting principles


I have an HTML file which contains two tabs like this (besides lots of other stuff):

<div id="tabs">
    <div id="tab1" class="">Tab 1</div>
    <div id="tab2" class="">Tab 2</div>
</div>

This HTML file is used in several contexts, so it seems reasonable to have one single HTML file that I include with PHP in order not to violate the Don't Repeat Yourself principle.

Depending on various conditions these tabs need to have different classes when the page loads. This is achieved through PHP, either

$tab1Class = 'active';
$tab2Class = 'inactive';

or

$tab1Class = 'inactive';
$tab2Class = 'active';

with this mixed HTML and PHP:

<div id="tabs">
    <div id="tab1" class="<?php echo $tab1Class;?>">Tab 1</div>
    <div id="tab2" class="<?php echo $tab2Class;?>">Tab 2</div>
</div>

My question is what would be considered best practice when having to balance between repeating code or inserting PHP into the HTML file - how much repetition is ok and how deep into the HTML is it ok to bury PHP snippets?

Is, for example, the following degree of separation better? The PHP isn't as deeply buried into the HTML here, but there's more code that I have to repeat in the PHP file(s) in order to generate the div elements every time.

<div id="tabs">
    <?php echo $tabs;?>
</div>

I understand that one possible answer is that this is something that has to be decided for each case individually, but if there are any principles that are more or less generally accepted it would be nice to hear about them.


Solution

  • IMHO first approach where you print just css classes is better. If you want to bring this to new level consider using some template engine, like Smarty or Twig. That way you can totally distinct your logic (code) from your presentation.