Using Feature Flags

How to enable feature flags in your templates.

Twig #

Use craft.featureFlags.isEnabled() to check whether a flag is enabled for the cur­rent user.

Con­di­tion­al block

{% if craft.featureFlags.isEnabled('new-hero') %}
    {% include '_partials/hero-v2' %}
{% else %}
    {% include '_partials/hero' %}
{% endif %}

Ternary for swap­ping a component

{% set layout = craft.featureFlags.isEnabled('wide-layout') ? 'wide' : 'default' %}
{% include '_layouts/' ~ layout %}

Cus­tom buck­et key

Pass a sec­ond argu­ment to over­ride the default buck­et­ing iden­ti­fi­er. This is use­ful when you want roll­out buck­et­ing tied to some­thing oth­er than the cur­rent user ID (e.g. a com­pa­ny account or ses­sion ID).

{% set companyId = currentUser.companyId %}
{% if craft.featureFlags.isEnabled('bulk-export', companyId) %}
    <a href="{{ url('export/bulk') }}">Bulk Export</a>
{% endif %}

How eval­u­a­tion works #

When you call isEnabled(), the plu­g­in eval­u­ates the flag in a fixed order. The first con­di­tion that pro­duces a defin­i­tive result wins.

  1. Flag exists? — If the flag han­dle doesn’t match any flag, return false.
  2. Enabled tog­gle — If the flag’s mas­ter tog­gle is off, return false.
  3. Expi­ra­tion — If the flag has an expi­ra­tion date that is in the past, return false.
  4. Glob­al on — If the flag has no tar­get­ing rules and no roll­out per­cent­age, return true (the flag is glob­al­ly on).
  5. Tar­get­ing rules — Each rule is eval­u­at­ed in order. If any rule match­es, return true. See Tar­get­ing Rules.
  6. Per­cent­age roll­out — If a roll­out per­cent­age is set and greater than 0, com­pute the user’s buck­et. If the buck­et falls with­in the per­cent­age, return true. See Per­cent­age Roll­outs.
  7. Default — If noth­ing matched, return false.

PHP #

Use the EvaluationService to check flags from PHP code:

use craftquest\featureflags\FeatureFlags;

$isEnabled = FeatureFlags::getInstance()->evaluationService->isEnabled('new-hero');
Para­me­terTypeDescrip­tion
$flagNamestringThe flag handle
$user?UserA spe­cif­ic user to eval­u­ate against. Defaults to the cur­rent­ly logged-in user in web requests, or null in con­sole requests.
$bucketKey?stringA cus­tom iden­ti­fi­er for per­cent­age roll­out buck­et­ing. Over­rides the default (user ID).

Pass­ing a spe­cif­ic user

use craft\elements\User;
use craftquest\featureflags\FeatureFlags;

$user = User::find()->email('[email protected]')->one();

if (FeatureFlags::getInstance()->evaluationService->isEnabled('beta-dashboard', $user)) {
    // show beta dashboard for this user
}

Pass­ing a cus­tom buck­et key

use craftquest\featureflags\FeatureFlags;

// Roll out by company rather than by individual user
$companyId = (string) $currentUser->companyId;

if (FeatureFlags::getInstance()->evaluationService->isEnabled('bulk-export', null, $companyId)) {
    // enable bulk export for this company
}