In case your template is not located in a file but in the database Twig allows you to render a string:

$twig_env = new Twig_Environment(new Twig_Loader_String);

$output = $twig_env->render('This is {{ foo }}', [
     'foo' => 'an ordinary string',
]);

// $output now contains: This is an ordinary string