HTML email template with str_replace

I have a form that I programmed with AngularJs. When the user submits which forms a php script (executed using Slim) that inserts the form data into the database and generates E-Mail (PHPmailer).

Now to the question:

I get the structure from email with get_contents_file from the template and replace str_replace placeholders.

template:

<h2>User Information</h2>

<table>
  <tbody>
    <tr><th>Firstname:</th><td>%firstname%</td></tr>
    <tr><th>Lastname:</th><td>%lastname%</td></tr>
  </tbody>
</table>
<br>

<h2>Other Information</h2>

<table>
  <tbody>
    <tr><th>Phone:</th><td>%phone%</td></tr>
    <tr><th>E-Mail:</th><td>%email%</td></tr>
    <tr><th>Organisation:</th><td>%organisation%</td></tr>
  </tbody>
</table>

My problem is that not all of these fields are required, and I want to delete the whole table + header if none of these variables (phone, email, organization).

+4
source share
2 answers

You can "hide" the table and not delete it.

Setting a parameter, for example:

<table style="display: %display-other-information%">

null, "none", , "normal".

, , , .

+1

, 2 , .

- :

function render($firstname, $lastname, $phone = null, $email = null, $organisation = null)
{
    $templatePath = (is_null($phone) && is_null($email) && is_null($organisation)) ?
    '/path/to/your/template/withought/the/contact/table.html':
    '/path/to/your/template/with/the/contact/table.html';

    $templateContent = file_get_contents($templatePath);

    $placeHolders = [
       '%firstname%',
        '%lastname%',
        '%phone%',
        '%email%',
        '%organisation%',
    ];

    $values = [
        $firstname,
        $lastname,
        $phone,
        $email,
        $organisation,
    ];

    $rendered = str_replace($placeHolders, $values, $templateContent);
    return $rendered;
}
+1

All Articles