How to pass variables to html render arrays with FormattableMarkup in drupal 8, 9 and 10

Mixing HTML with variables is common practice when developing custom applications. This snippet shows how to mix HTML and variables the correct way.

use Drupal\Component\Render\FormattableMarkup;

$output = new FormattableMarkup('<h2>@title</h2>', ['@title' => $entity->label()]);

More about the FormattableMarkup class here.

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!