Условия и switch/case

Полное руководство по условным конструкциям в шаблонах MNRFY

Базовые условия if/else

Простое условие

<!-- Простая проверка -->
{% if user %}
    <p>Добро пожаловать, {{ user.name }}!</p>
{% endif %}

<!-- Проверка свойства -->
{% if user.is_active %}
    <span class="badge badge-green">Активный</span>
{% endif %}

Условие с альтернативой

<!-- IF/ELSE -->
{% if user.balance > 0 %}
    <span class="balance-positive">{{ user.balance | money('₽') }}</span>
{% else %}
    <span class="balance-zero">Пополните баланс</span>
{% endif %}

<!-- Авторизация -->
{% if user %}
    <a href="/profile">Профиль</a>
    <a href="/logout">Выход</a>
{% else %}
    <a href="/login">Вход</a>
    <a href="/register">Регистрация</a>
{% endif %}

Множественные условия

<!-- ELSEIF -->
{% if user.role == 'admin' %}
    <span class="badge badge-red">Администратор</span>
{% elseif user.role == 'moderator' %}
    <span class="badge badge-yellow">Модератор</span>
{% elseif user.is_premium %}
    <span class="badge badge-blue">Премиум</span>
{% else %}
    <span class="badge badge-gray">Пользователь</span>
{% endif %}

Операторы сравнения

Основные операторы

<!-- Равенство -->
{% if status == 'active' %}
    <span class="status-active">Активен</span>
{% endif %}

<!-- Неравенство -->
{% if role != 'guest' %}
    <a href="/admin">Панель управления</a>
{% endif %}

<!-- Сравнение чисел -->
{% if user.age >= 18 %}
    <p>Доступ к контенту для взрослых разрешен</p>
{% endif %}

{% if product.price < 1000 %}
    <span class="badge badge-green">Бюджетный</span>
{% endif %}

Строгое сравнение

<!-- Строгое равенство (тип + значение) -->
{% if user.id === '123' %}
    <p>ID пользователя строго равно строке '123'</p>
{% endif %}

<!-- Строгое неравенство -->
{% if count !== 0 %}
    <p>Количество не равно нулю (проверка типа)</p>
{% endif %}

Логические операторы

AND (и)

<!-- Логическое И -->
{% if user and user.is_active %}
    <p>Пользователь существует и активен</p>
{% endif %}

{% if user.age >= 18 and user.verified %}
    <button class="btn-premium">Премиум функции</button>
{% endif %}

<!-- Сложные условия -->
{% if user.balance > 100 and user.ban == 0 and user.verified %}
    <a href="/vip-section">VIP раздел</a>
{% endif %}

OR (или)

<!-- Логическое ИЛИ -->
{% if user.is_admin or user.is_moderator %}
    <a href="/admin">Панель управления</a>
{% endif %}

{% if product.on_sale or product.featured %}
    <span class="badge badge-special">Специальное предложение</span>
{% endif %}

NOT (не)

<!-- Логическое НЕ -->
{% if not user.is_banned %}
    <p>Добро пожаловать!</p>
{% endif %}

{% if not (user.role == 'guest') %}
    <a href="/dashboard">Личный кабинет</a>
{% endif %}

Проверки существования и типов

Проверка существования

<!-- Проверка определения переменной -->
{% if isset(user) %}
    <p>Переменная user определена</p>
{% endif %}

<!-- Проверка на null -->
{% if is_null(user.avatar) %}
    <img src="{{ asset('images/default-avatar.png') }}" alt="Аватар по умолчанию">
{% else %}
    <img src="{{ user.avatar }}" alt="Аватар">
{% endif %}

<!-- Проверка на пустоту -->
{% if empty(user.bio) %}
    <p> - </p>
{% else %}
    <p>{{ user.bio }}</p>
{% endif %}

Проверки типов

<!-- Проверка на число -->
{% if is_numeric(count) %}
    <p>Количество: {{ count }}</p>
{% endif %}

<!-- Проверка на строку -->
{% if is_string(message) %}
    <p>{{ message }}</p>
{% endif %}

<!-- Проверка на массив -->
{% if items is iterable %}
    <ul>
    {% foreach items as item %}
        <li>{{ item }}</li>
    {% endforeach %}
    </ul>
{% endif %}

<!-- Проверка на массив 2 -->
{% if is_array(items) %}
    <ul>
    {% foreach items as item %}
        <li>{{ item }}</li>
    {% endforeach %}
    </ul>
{% endif %}

Switch/Case конструкция

Базовый switch

{% switch user.role %}
    {% case 'admin' %}
        <span class="role-badge admin">
            <i class="fas fa-crown"></i> Администратор
        </span>
    {% case 'moderator' %}
        <span class="role-badge moderator">
            <i class="fas fa-shield-alt"></i> Модератор
        </span>
    {% case 'premium' %}
        <span class="role-badge premium">
            <i class="fas fa-star"></i> Премиум
        </span>
    {% default %}
        <span class="role-badge user">
            <i class="fas fa-user"></i> Пользователь
        </span>
{% endswitch %}

Switch со статусами

{% switch order.status %}
    {% case 'pending' %}
        <div class="status-pending">
            <i class="fas fa-clock"></i>
            <span>Ожидает обработки</span>
        </div>
    {% case 'processing' %}
        <div class="status-processing">
            <i class="fas fa-spinner fa-spin"></i>
            <span>В обработке</span>
        </div>
    {% case 'shipped' %}
        <div class="status-shipped">
            <i class="fas fa-truck"></i>
            <span>Отправлен</span>
        </div>
    {% case 'delivered' %}
        <div class="status-delivered">
            <i class="fas fa-check-circle"></i>
            <span>Доставлен</span>
        </div>
    {% case 'cancelled' %}
        <div class="status-cancelled">
            <i class="fas fa-times-circle"></i>
            <span>Отменен</span>
        </div>
    {% default %}
        <div class="status-unknown">
            <i class="fas fa-question"></i>
            <span>Неизвестный статус</span>
        </div>
{% endswitch %}

Множественные случаи

{% switch user.subscription %}
    {% case 'trial' %}
    {% case 'free' %}
        <div class="subscription-free">
            <h3>Бесплатный доступ</h3>
            <p>Ограниченные возможности</p>
        </div>
    {% case 'basic' %}
    {% case 'standard' %}
        <div class="subscription-paid">
            <h3>Платная подписка</h3>
            <p>Расширенные возможности</p>
        </div>
    {% case 'premium' %}
    {% case 'enterprise' %}
        <div class="subscription-premium">
            <h3>Премиум подписка</h3>
            <p>Все возможности включены</p>
        </div>
    {% default %}
        <div class="subscription-unknown">
            <h3>Неизвестная подписка</h3>
        </div>
{% endswitch %}

Сложные условия

Вложенные условия

{% if user %}
    {% if user.is_active %}
        {% if user.email_verified %}
            <div class="user-verified">
                <p>Добро пожаловать, {{ user.name }}!</p>
                {% if user.is_premium %}
                    <a href="/premium-features">Премиум возможности</a>
                {% endif %}
            </div>
        {% else %}
            <div class="email-verification-required">
                <p>Подтвердите email адрес</p>
                <a href="/verify-email">Отправить письмо повторно</a>
            </div>
        {% endif %}
    {% else %}
        <div class="user-inactive">
            <p>Ваш аккаунт заблокирован</p>
        </div>
    {% endif %}
{% else %}
    <div class="guest-user">
        <p>Войдите в систему для доступа к дополнительным возможностям</p>
        <a href="/login">Войти</a>
    </div>
{% endif %}

Комбинирование условий

<!-- Сложные логические выражения -->
{% if (user.role == 'admin' or user.role == 'moderator') and user.is_active==true and user.is_banned==false %}
    <div class="admin-panel">
        <a href="/admin/users">Управление пользователями</a>
        <a href="/admin/content">Управление контентом</a>
    </div>
{% endif %}

<!-- Проверка диапазонов -->
{% if product.price >= 100 and product.price <= 1000 %}
    <span class="price-range-middle">Средняя ценовая категория</span>
{% endif %}

Условные CSS классы

Динамические классы

<!-- Условные классы в атрибутах -->
<div class="user-card {{ user.is_online ? 'online' : 'offline' }}">
    <span class="status {{ user.is_premium ? 'premium' : 'regular' }}">
        {{ user.name }}
    </span>
</div>

<!-- Множественные условные классы -->
{% set user_classes = [] %}
{% if user.is_online %}
    {% set user_classes = user_classes | push('online') %}
{% endif %}
{% if user.is_premium %}
    {% set user_classes = user_classes | push('premium') %}
{% endif %}
{% if user.is_verified %}
    {% set user_classes = user_classes | push('verified') %}
{% endif %}

<div class="user {{ user_classes | join(' ') }}">
    {{ user.name }}
</div>

Условные атрибуты

<!-- Условные атрибуты -->
<button {{ user.can_edit ? '' : 'disabled' }}>Редактировать</button>

<input type="text" 
       value="{{ form.title }}"
       {{ form.readonly ? 'readonly' : '' }}
       {{ form.required ? 'required' : '' }}>

<a href="{{ user.profile_url }}" 
   {{ user.is_external ? 'target="_blank"' : '' }}>
    {{ user.name }}
</a>

Практические примеры

Система уведомлений

{% if notifications %}
    <div class="notifications">
        {% foreach notifications as notification %}
            {% switch notification.type %}
                {% case 'success' %}
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        {{ notification.message }}
                    </div>
                {% case 'warning' %}
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        {{ notification.message }}
                    </div>
                {% case 'error' %}
                    <div class="alert alert-danger">
                        <i class="fas fa-times-circle"></i>
                        {{ notification.message }}
                    </div>
                {% default %}
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        {{ notification.message }}
                    </div>
            {% endswitch %}
        {% endforeach %}
    </div>
{% endif %}

Навигационное меню

<nav class="main-navigation">
    <ul>
        {% foreach menu_items as item %}
            {% if not item.auth_required or user %}
                {% if not item.permission_required or user.hasPermission(item.permission_required) %}
                    <li class="{{ item.is_active ? 'active' : '' }}">
                        <a href="{{ item.url }}">
                            {% if item.icon %}
                                <i class="fas fa-{{ item.icon }}"></i>
                            {% endif %}
                            {{ item.title }}
                            {% if item.badge %}
                                <span class="badge">{{ item.badge }}</span>
                            {% endif %}
                        </a>
                    </li>
                {% endif %}
            {% endif %}
        {% endforeach %}
    </ul>
</nav>
Следующий шаг: Изучите циклы и итерации.