2013-11-09 13:34:25
標(biāo)簽:
smartyecshop數(shù)學(xué)運(yùn)算在ecshop的使用中,smarty可以很方便的做成網(wǎng)頁(yè)。但ecshop的smarty把一些功能去掉了,只保留了邏輯運(yùn)算、變量處理
等功能,連數(shù)學(xué)計(jì)算都不支持。我們想要在smarty模板中對(duì)一個(gè)變量進(jìn)行動(dòng)態(tài)的計(jì)算,就沒有辦法。
研究了一個(gè)晚上,終于可以讓ecshop的smarty模板支持簡(jiǎn)單的數(shù)學(xué)計(jì)算了。
在ecshop的smarty模板中,對(duì)變量處理如下:
{$foo+ 1}
那么生成的后臺(tái)代碼是這樣的:
<?php echo$this->_var['foo+1'] ; ?>
它將$號(hào)后面的全部作為變量名了。
我們要的效果,
模板中是這樣:
{math equation="$foo + 1"}
在后臺(tái)生成這樣的代碼:
<?php echo$this->_var['foo] + 1; ?>
這里需要對(duì)cls_template文件進(jìn)行修改,讓其支持math標(biāo)簽。
在select 方法中增加一個(gè)case:
1
2
3
4
case'math':
$t= $this->get_math_para(substr($tag, 8));
return'<?php echo '. $t. '; ?>';
break;
增加一個(gè)方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 處理math中的公式.
* */
functionget_math_para($val){
$pa= $this->str_trim($val);
foreach($paAS $value)
{
if(strrpos($value, '='))
{
list($a, $b) = explode('=', str_replace(array(' ', '"', "'", '"'), '', $value));
if(strpos($b, '$') >= 0)
{
//$b為類似的1+2,$abc*123等
$pattern= "/\\$[_a-zA-z]+[a-zA-Z0-9_]*/";
preg_match($pattern, $b,$arr);
if($arr) {
foreach($arras$match) {
$v= $this->get_val(substr($match, 1));
$b= str_replace($match, $v, $b);
}
}
}
}
}
return$b;
}
這樣就可以了。