Rendering Twig templates programmatically in Drupal 8
From time to time, I have the need to take a Twig template and a set of variables, render the template, replacing all the variables within, and then get the output as a string. For example, if I want to have a really simple email template in a custom module which has a variable for first_name
, so I can customize the email before sending it via Drupal or PHP, I could do the following in Drupal 7: