Cookbook
Building a nav menu from voyti's routes
Voyti does not provide a menu model or navigation contract (see
Routes) - it only exposes named routes that the
host application wires into its own menu, sidebar, or access rules. For example, a
yiisoft/yii-bootstrap5
nav built from those routes might look like:
use Yiisoft\Yii\Bootstrap5\Nav;
use Yiisoft\Yii\Bootstrap5\NavLink;
echo Nav::widget()->items(
NavLink::to($this->translator->translate('voyti.view.login.title', category: 'voyti'), $this->url->generate('voyti/session-login'))
->visible($this->currentUser->isGuest()),
NavLink::to('User', $this->url->generate('voyti/user'))
->active(str_starts_with($this->currentRoute->getName() ?? '', 'voyti/user'))
->visible(!$this->currentUser->isGuest()),
NavLink::to('Admin', $this->url->generate('voyti/admin'))
->active(str_starts_with($this->currentRoute->getName() ?? '', 'voyti/admin'))
->visible($this->authManager->userHasPermission($this->currentUser->getId(), 'voyti-admin')),
);
voyti/session-logout only accepts POST, so it can't be a
plain NavLink. Render it as its own small form instead, styled to match
the nav:
use Yiisoft\Html\Html;
if (!$this->currentUser->isGuest()) {
echo Html::li()->class('nav-item')->open();
echo Html::form()->post($this->url->generate('voyti/session-logout'))->csrf($csrf)->open();
echo Html::submitButton($this->translator->translate('voyti.menu.logout', category: 'voyti'))
->class('nav-link', 'btn', 'btn-link');
echo Html::form()->close();
echo Html::li()->close();
}
$csrf here is the Csrf value object that
Yiisoft\Yii\View\Renderer\CsrfViewInjection
makes available to views when it's registered as a common parameter injection.
Showing the impersonation banner in your own layout
When an admin uses voyti/admin-users-switch-identity
to temporarily assume another user's identity, drop in
YiiRocks\Voyti\Widget\SwitchIdentityWidget anywhere in your layout to show
the "you're logged in as this user" banner with a restore button:
echo YiiRocks\Voyti\Widget\SwitchIdentityWidget::widget();
Its dependencies resolve through the DI container, so this needs no wiring beyond having voyti installed, and it renders an empty string when nobody is impersonating anyone.