HTML E-Mail 模板 str_replace

HTML E-Mail Template with str_replace

我有一个表格,我用 AngularJs 编写了它。当用户提交 形成一个 php 脚本(用 Slim 制作)被执行,它将表单数据插入数据库并生成一个 E-Mail (PHPmailer)。

现在回答问题:

我从模板中使用 file_get_contents 从电子邮件中获取结构,并将占位符替换为 str_replace。

模板:

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

我的问题是并非所有这些字段都是必需的,我想删除 整个 table + 如果 none 这些变量的标题(phone、电子邮件、 组织)已设置。

最好创建 2 个不同的模板,有和没有 table,并根据 phone、电子邮件和组织的存在呈现其中一个。

类似于:

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

您可以 "hide" table,而不是删除。

设置参数,例如:

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

如果您的属性为空,则必须设置 "none",如果不是,则设置 "normal"。

更好的解决方案是创建其他模板,但是,如果您不想,也可以这样做,就像我说的那样。