在编译之前从php访问模板中的var

时间:2014-01-09 14:54:42

标签: php smarty

我想在模板文件中可以限制结果的数量,如下所示:

file.tpl

{$box_count = 10}

{foreach $box}
.
.
.
{/foreach}

如何在php中处理并获取此变量以限制数据库中的结果?

示例:

<?php
$smarty = new Smarty;


$count = ... //HOW CAN GET ?

$data = array();
$q = mysql_query( "SELECT * FROM `users` LIMIT 0,$count" );
while( $r = mysql_fetch_array( $q ) )
{
    $data[] = $r;
}
$smarty->assign( 'box' , $data );

$smarty->dipslay( 'file.tpl' );
?>

注意: 因为这个var只是在tpl文件中定义的,getTemplateVars()中不存在。

感谢

1 个答案:

答案 0 :(得分:0)

我使用registerObject解决了这个问题:

<?php
$smarty = new Smarty;

class Test
{
    public function setCount( $params , &$smarty )
    {
        $count = $params['count'];

        $data = array();
        $q = mysql_query( "SELECT * FROM `users` LIMIT 0,$count" );
        while( $r = mysql_fetch_array( $q ) )
        {
            $data[] = $r;
        }
        $smarty->assign( 'box' , $data );
    }
}

$S = new Test;
$smarty->registerObject( 'Test' , $S , array( 'setCount' ) )

$smarty->dipslay( 'file.tpl' );
?>

file.tpl:

{Test->setCount count="10"}
{foreach $box}
.
.
.
{/foreach}