简体   繁体   中英

HTML E-Mail Template with str_replace

I have a form, which i have programmed with AngularJs. When the user submits that form a php script (made with Slim) gets executed, which inserts the formdata into the DB and generates an E-Mail (PHPmailer).

Now to the question:

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

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 + the heading if none of these variables (phone, email, organisation) is set.

Best if you create 2 different templates, with and without that table, and render one of them according to the existence of phone, email and organisation.

Something like:

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

You can "hide" the table, instead of remove.

Setting a parameter, like:

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

If your properties are null, you have to set "none", if not, set "normal".

The better solution, is to create other templates, but, if you don't want, you can do this, like I said.

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