如何将数据正确传递到 Codeigniter4 中用于 html 电子邮件模板的视图?

How can I properly pass data into a view intended for html email template in Codeigniter4?

我正在尝试将数据传递到一个视图中,该视图的内容将作为 html 电子邮件发送。视图文件正在正确加载并且电子邮件已发送,只是它没有显示我一起传递的数据。

下面是代码

控制器

<?php 

$content = '<p style="font-size: 14px; line-height: 140%; text-align: center;"> <span style="font-size: 16px; line-height: 22.4px;"> This is a content to be passed </span> </p>';
                
$item = [
    'title' => 'This is an amazing title',
    'message' => $content
];
                    
$message = view('email_template', $item); //email_template is a view that loads fine but the $item is not accessed inside of it.

?>

//email_template.php

<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
</head>

<body>
<?php print_r($item) ?>
</body>

</html>

如果你想获取 view 中的项目,请使用这样的数组

$item['item'] = [
    'title' => 'This is an amazing title',
    'message' => $content
];

使用 compact

的另一个函数
$item = [
    'title' => 'This is an amazing title',
    'message' => $content
];
$message = view('email_template', compact('item'));
<?php 

$data['content'] = '<p style="font-size: 14px; line-height: 140%; text-align: center;"> <span style="font-size: 16px; line-height: 22.4px;"> This is a content to be passed </span> </p>';
                
$data['item'] = [
    'title' => 'This is an amazing title',
    'message' => $content
];
                    
$message = view('email_template', $data); //email_template is a view that loads fine but the $item is not accessed inside of it.

?>

然后在您看来,您将可以访问数组键作为变量。

因此,要访问 $data['content'],您将使用:

<?php echo $content ?> 

要访问标题和消息:

<?php echo $item['title'] ?>

<?php echo $item['message'] ?>

要了解有关如何将数据发送到视图的更多信息,您可以在此处查看文档:https://codeigniter.com/user_guide/outgoing/views.html?highlight=views#adding-dynamic-data-to-the-view