Yii2 传递参数到邮件布局

Yii2 pass parameters to mail layout

在使用 Yii mailer class 时,是否有任何方法可以在邮件布局中访问您的参数?我可以从视图访问 $model,但不能访问布局。

<?php

        $params = array(
           "model" => $model
        );

        $message = Yii::$app->mailer->compose([
            'html' => $view.'Html',
            'text' => $view,
        ], $params)
        ->setFrom("me@placeholder.com")
        ->setTo($recipient)
        ->setSubject($subject);
?>

我知道对于标准 Web 视图,您可以设置 yii\web\View::$params 以访问布局中的变量,但这似乎不适用于邮件程序。

有什么想法吗?

我会做一些类似于将面包屑返回视图的操作。

//In your view file, model was passed down via compose as you have it.
//this adds model element to the View object's params.
$this->params['model'] = $model; 

//In your layout
echo $this->params['model']->attribute;

我刚刚发现了另一种从控制器将参数设置为布局的方法:

// In your controler before send mail : 
Yii::$app->mailer->view->params['title'] = $title;

// In your layout
echo $this->params['title'];

希望对您有所帮助!

我有同样的问题,现在你传递的参数可以直接在邮件模板中作为变量调用:

// In controller
<?php
$params = [
    'username' => 'diegouser',
    'password' => 'supersecret',
];

Yii::$app->mailer->compose([
            'html' => 'layouts/' . $view . '-html',
            'text' => 'layouts/' . $view . '-text',
        ], $params)
        ->setFrom($mailFrom)
        ->setTo($emailTo)
        ->setSubject($subject)
        ->send();

所以你可以只回显布局中的变量:

<?php
// In email layout:
<?= $username ?>
<?= $password ?>