Q:

Parse variables into twig email template from custom module

I'm trying to send an email from my module and am trying to pass some vars into my module template that I can render using twig. Please note that this is a module template not a front end template.
$first = "john";
$last = "doe";
$mailTo = "john@example.co.uk";
$mailer = Craft::$app->getMailer();
$mailer->htmlLayout = false;
$mailer->textLayout = false;
$mailer->setViewPath('@modules/businessmodule/templates/emails');
$mailer->compose('failed_payment.twig', ['first' => $first, 'last' => $last])
        ->setTo($mailTo)
        ->setSubject('Failed Payment')
        ->setTextBody('Text fallback')
        ->send();

But I cannot access the vars in my twig template like {{ first }}.
i.e
<p>
    Hi, sorry it didn't work out {{ first }} {{ last }}
</p>

Am i missing some parse method somewhere?

A:

So, you have to "switch" template modes from the look of it! (who knew?!)
This is the code you need to use templates within your module directory, assuming you have your modules template root defined as Oli referenced.
$first = "john";
$last = "doe";
$params = ['first' => $first, 'last' => $last];
$mailTo = "john@example.co.uk";

// Switch the template mode
$oldMode = Craft::$app->view->getTemplateMode();
Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_CP);

$mailer = Craft::$app->getMailer();
$mailer->compose()
        ->setTo($mailTo)
        ->setSubject('Failed Payment')
        ->setHtmlBody(
            Craft::$app->getView()->renderTemplate('business-module/emails/failed_payment.twig',
            ['user' => $params])
        )
        ->send();

// Switch the template mode back
Craft::$app->view->setTemplateMode($oldMode);

This took far far too much time to fathom for my liking!

