【发布时间】:2011-10-25 11:51:21
【问题描述】:
我有不同语言的邮件模板,并且在这个模板中使用了一些 php 变量。我必须将模板存储在数据库中,在发送邮件之前,接收当前语言的模板并替换所有 php 变量。虽然我在视图的帮助下这样做 - 没有问题,但现在我不知道如何替换模板中的 php vars? 或者也许有更好的方法来解决这个问题?我只需要能够从管理员端编辑模板。
【问题讨论】:
标签: php database templates codeigniter
我有不同语言的邮件模板,并且在这个模板中使用了一些 php 变量。我必须将模板存储在数据库中,在发送邮件之前,接收当前语言的模板并替换所有 php 变量。虽然我在视图的帮助下这样做 - 没有问题,但现在我不知道如何替换模板中的 php vars? 或者也许有更好的方法来解决这个问题?我只需要能够从管理员端编辑模板。
【问题讨论】:
标签: php database templates codeigniter
为什么不将变量存储在电子邮件模板中作为非 PHP 的东西,例如 ..
Thank you %name% for registering!
这使得管理员编辑变得容易。
然后在您发送之前的代码中,您有一个包含所有要替换的变量的数组...
$template = $this->load->view('email_template.html', '', true);
foreach ($vars as $key => $value) {
$template = str_replace('%' . $key . '%', $value, $template);
}
编辑
为了回应您在下面的评论,我会在数组中设置语言,然后在视图中使用 PHP 来输出正确的语言,然后进行替换...
// List of message translations
$messages = array(
'en' => array(
'thank_you' => 'Thank you %name% for registering!',
'username_details' => 'Your username is %username%'
),
'fr' => array(
'thank_you' => 'Merci %name% de l\'enregistrement!',
'username_details' => 'Votre username est %username%'
)
);
// Variables to replace
$vars = array(
'name' => 'John Smith',
'username' => 'john'
);
// Choose language
$lang = 'en';
// Load the template
$template = $this->load->view('email_template.html', array('messages' => $messages, 'lang' => $lang), true);
// Replace the variables
foreach ($vars as $key => $value) {
$template = str_replace('%' . $key . '%', $value, $template);
}
email_template.html
<html>
<body>
<p><?php echo $messages[$lang]['thank_you']; ?></p>
<hr />
<p><?php echo $messages[$lang]['username_details']; ?></p>
</body>
</html>
【讨论】:
Thank you %name% for registering! 文本是英文的,我需要为不同的语言提供不同的模板。所以不会只有文件email_template.html