【问题标题】:Yii2 pass parameters to mail layoutYii2 传递参数给邮件布局
【发布时间】:2015-08-13 14:34:27
【问题描述】:

在使用Yii mailer 类时,有什么方法可以在邮件布局中访问您的参数?我可以从视图访问$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 以访问布局中的变量,但这似乎不适用于邮件程序。

有什么想法吗?

【问题讨论】:

    标签: php yii2 swiftmailer


    【解决方案1】:

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

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

    希望对您有所帮助!

    【讨论】:

      【解决方案2】:

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

      //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;
      

      【讨论】:

      • 谢谢。不幸的是,我需要在我的每一个电子邮件视图中都这样做,但这比复制页眉/页脚 html 好得多
      【解决方案3】:

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

      // 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 ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-18
        • 1970-01-01
        • 1970-01-01
        • 2015-12-21
        相关资源
        最近更新 更多