调用html模板显示数据,通过str_replace()显示html模板中的数组数据

"博客讨论了在PHP类中如何处理HTML电子邮件模板,特别是如何在模板中循环替换产品数组的数据。作者遇到的问题是如何将产品订单(包含名称、价格和数量的数组)的详细信息插入到模板的{{variable}
摘要由CSDN通过智能技术生成

我正在处理一个PHP类,在这里我用数据替换变量到HTML电子邮件模板文件。它通过将数据替换为“{{first_name}}”这样的字符串。通过str_replace()显示html模板中的数组数据

这样,我可以用一个客户的正确数据替换像first_name,last_name,email等变量。这对单值很好,但现在我有一个问题。

在这封电子邮件中,我展示了客户订购的产品。这是一个阵列产品,每个产品都有自己的规格(请看下面的示例数组)。

问题: 有没有人有一个想法,我可以如何实现用产品数组的循环替换{{variable}}?

产品阵列例如:

$products = array(

array(

'name' => 'Product 1',

'price' => 10.00,

'qty' => 1

),

array(

'name' => 'Product 2',

'price' => 12.55,

'qty' => 1

),

array(

'name' => 'Product 3',

'price' => 22.10,

'qty' => 3

)

);

我的类别:

class ConfirmationEmail {

protected $_openingTag = '{{';

protected $_closingTag = '}}';

protected $_emailValues;

protected $_template;

/**

* Email Template Parser Class.

* @param string $templatePath HTML template string OR File path to a Email Template file.

*/

public function __construct($templatePath) {

$this->_setTemplate($templatePath);

}

/**

* Set Template File or String.

* @param string $templatePath HTML template string OR File path to a Email Template file.

*/

protected function _setTemplate($templatePath) {

$this->_template = file_get_contents($templatePath);

}

/**

* Set Variable name and values one by one or at once with an array.

* @param string $varName Variable name that will be replaced in the Template.

* @param string $varValue The value for a variable/key.

*/

public function setVar($varName, $varValue) {

if(! empty($varName) && ! empty($varValue)) {

$this->_emailValues[$varName] = $varValue;

}

}

/**

* Set Variable name and values with an array.

* @param array $varArray Array of key=> values.

*/

public function setVars(array $varArray) {

if(is_array($varArray)) {

foreach($varArray as $key => $value) {

$this->_emailValues[$key] = $value;

}

}

}

/**

* Returns the Parsed Email Template.

* @return string HTML with any matching variables {{varName}} replaced with there values.

*/

public function output() {

$html = $this->_template;

foreach($this->_emailValues as $key => $value) {

if(! empty($value)) {

$html = str_replace($this->_openingTag . $key . $this->_closingTag, $value, $html);

}

}

return $html;

}

}

在动作:

$template_path = 'path-to-template/email-templates/confirmation.php';

$emailHtml = new ConfirmationEmail($template_path);

$emailHtml->setVars(array(

'first_name' => 'Jack',

'last_name' => 'Daniels',

'street' => 'First street',

'number' => '22',

// Other data

));

// Outputs the HTML

echo $emailHtml->output();

Ps。如果需要,我可以向您显示HTML电子邮件模板。这是一个包含内联样式和需要替换数据的地方{{variables}}的很多表格的html结构。

2015-09-08

Robbert

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值