Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinszeltins's avatar

How to avoid mixing PHP code in View and vice versa?

I am learning to write better code and to not mix PHP code with HTML/CSS since that will be better both for me and people who will read my code after me. However I stumbled upon a situation where I have users with different roles and each role has it's own color/class/style/html. I end up putting either HTML code in my PHP logic or vice versa. Is there a nice way around this?

In Controller:

if ($user_role == 'administrator') {
    $user_color == '#ff0000'; <-- CSS Style in my PHP
    $user_class == 'admin-class'; <-- CSS Class in my PHP
}

$users = [
    'username' => 'John',
    'user_color' => '#ff0000' <-- CSS Style in my PHP
]

In my View:

<a class="{{ $user_class }} style="color: {{ $user_color }}">Administrator</a>
or if I did not want HTML or CSS in my PHP then I end up putting PHP in my HTML.

In my View:

foreach($users as $user):
    // Too much PHP logic in my HTML view
    if ($user->role == 'administrator') {
        $user_color = 'red';
    } else if ($user->role == moderator) {
        $user_color = '#00ff00'
    }

    <a style="color: {{ $user_color }}">{{ $user->username }}</a>
endforeach;

So either way, I end up mixing the two together. This is just one example where I need to adjust the HTML depending on some logic or conditions.

0 likes
2 replies
aurawindsurfing's avatar

@martinzeltin why not create custom properties on your modes such as:

public function isAdmin()
    {
        return $this->........... ? true : false;
    }

and then just call those in your view to check. Or you want to avoid doing checks in your view altogether?

Please or to participate in this conversation.