Search code examples
phpcodeigniter-4

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>

Solution

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