带有str_replace的HTML电子邮件模板

时间:2015-06-22 11:39:12

标签: php html templates phpmailer str-replace

我有一个表格,我用AngularJs编程。当用户提交时 执行形成一个php脚本(由Slim制作),将formdata插入数据库并生成一个电子邮件(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>

我的问题是并非所有这些字段都是必需的,我想要删除 如果没有这些变量(电话,电子邮件,整个表格+标题) 组织)已经确定。

2 个答案:

答案 0 :(得分: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 :(得分:1)

您可以“隐藏”表格,而不是删除。

设置参数,例如:

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

如果您的属性为null,则必须设置“none”,否则设置为“normal”。

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

相关问题