我正在设计我的html电子邮件,这些是包含变量的html块,我可以存储在$ template变量中.
我的问题在于存储在变量部分.将我的所有html放入php使得它成为一个痛苦的工作.
例如,下面的代码适用于简单的电子邮件,但一旦我开始获得嵌套表等,它将变得非常令人困惑...
$template.= 'Welcome ' . $username . '<br /><br /><br />';
$template.= 'Thank-you for creating an account <br /><br />';
$template.= 'Please confirm your account by click the link below! <br /><br />';
$template.= '<a href="' . $sitepath . '?email=' . $email . '&conf_key=' . $key . '" style="color: #03110A;"><font size="5" font-family="Verdana, Geneva, sans-serif" color="#03110A">' . $key . '</font></a>';
$template.='</body></html>';
Run Code Online (Sandbox Code Playgroud)
有没有办法我仍然可以将html存储在$ var中,但不必像这样写它?
gro*_*gel 12
对于电子邮件,我是基于文件的模板和真正基本的模板解析器的忠实粉丝.这样做的一个优点是客户和领域专家可以阅读甚至编辑文本.另一个是你不依赖于变量范围,就像heredoc一样.我做这样的事情:
电子邮件模板的文本文件:
Welcome, [Username]
Thank you for creating an account.
Please ... etc.
Run Code Online (Sandbox Code Playgroud)
PHP客户端代码:
$templateData = array ('Username'=>$username...); // get this from a db or something in practice
$emailBody = file_get_contents ($templateFilePath);// read in the template file from above
foreach ($templateData as $key => $value){
$emailBody = str_replace ("[$key]", $value, $emailBody);
}
Run Code Online (Sandbox Code Playgroud)
当然,如果您的电子邮件需要包含文本[用户名],您将遇到麻烦,但您可以提出自己的伪代码约定.对于包含循环和条件之类的html或更复杂的电子邮件,您可以扩展这个想法,但使用模板引擎更容易,更安全.我喜欢PHPTAL,但它拒绝做纯文本.
编辑:对于电子邮件,您可能需要纯文本版本和HTML版本.使用函数或方法加载文件并进行替换使得添加第二种格式非常轻松.
您是否尝试过使用heredoc语法?
$template = <<<TEMPLATE
Welcome $username <br/><br/>
...
</body></html>
TEMPLATE;
Run Code Online (Sandbox Code Playgroud)
<?php ob_start(); ?>
Welcome <?= $username ?><br /><br /><br />
Thank-you for creating an account <br /><br />
Please confirm your account by click the link below! <br /><br />
<a href="<?= $sitepath ?>?email=<?= $email ?>&conf_key=<?= $key ?>" style="color: #03110A;"><font size="5" font-family="Verdana, Geneva, sans-serif" color="#03110A"><?= $key ?></font></a>
</body></html>
<?php
$template = ob_get_content();
// to output the data:
ob_end_flush();
// or
echo $template;
// or whatever you want to do else with `$template`
Run Code Online (Sandbox Code Playgroud)
有关此问题的更多信息,请参见http://www.php.net/manual/en/ref.outcontrol.php
更新:(致Ycros的积分)
template_file.php:
<html><head></head><body>
Welcome <?= $username ?><br /><br /><br />
Thank-you for creating an account <br /><br />
Please confirm your account by click the link below! <br /><br />
<a href="<?= $sitepath ?>?email=<?= $email ?>&conf_key=<?= $key ?>" style="color: #03110A;"><font size="5" font-family="Verdana, Geneva, sans-serif" color="#03110A"><?= $key ?></font></a>
</body></html>
Run Code Online (Sandbox Code Playgroud)
some_library_file.php
<?php
function load_template_to_string($file_name) {
ob_start();
include $file_name;
return ob_get_content();
}
Run Code Online (Sandbox Code Playgroud)
在要加载此模板的脚本中:
$template = load_template_to_string('template_file.php');
Run Code Online (Sandbox Code Playgroud)