我正在写一个邮件类,它将内容存储在数据库中并将其加载到模板中,然后将其作为HTML电子邮件发送。但是,由于每封电子邮件都包含PHP变量和动态内容,因此我决定使用分隔符。因此,而不是内容看起来像:用PHP变量替换分隔符
Hello $username, welcome to the site.
它会看起来像:
Hello {{username}}, welcome to the site.
到目前为止我用这些方法:
function load($name,$content)
{
// preps the template for HTML
}
function content($template_id)
{
$template = $this->db->get_where('email_templates',array('id'=>$template_id));
return $template->content;
}
function new_email($email,$name,$user_type)
{
$msg = $this->load($name,$this->content(1));
$this->send($email,'Thanks for your application',$msg,1);
}
我有麻烦是如何将{{variable}}转换为$变量以便解析 - 我不希望它仅仅作为$ username加载到电子邮件模板中。它只是使用正则表达式并转义字符串以便解析的情况吗?类似于:
$content = str_replace("{{","'.$",$template->content);
$content = str_replace("}}",".'",$template->content);
或者这是否有缺陷?有人知道什么是最好的做法吗?
对此使用正则表达式。如果你以后想要实现任何类型的逻辑(循环或嵌套的条件),那么让我在那里阻止你。使用现有的实现。存在轻量级模板引擎,并且231个类中的一个将肯定支持您所需的双重卷曲语法。 – mario