简体   繁体   中英

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

I am trying to pass data into a view from which contents will be sent as an html email. The view file is loading properly and email delivers except that it doesn't show the data I have passed alongside.

Below is the code

Controller

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

If you want to get item in view use array like this

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

one more function using 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.

?>

Then in your view you'll have access to your array keys as variables.

So to access the $data['content'] you'll use:

<?php echo $content ?> 

To access the title and message:

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

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

To know more about how to send data to the view you can check the documentation here: https://codeigniter.com/user_guide/outgoing/views.html?highlight=views#adding-dynamic-data-to-the-view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM