2011-12-28 37 views
5

嗨,我已经在.php文件中写了一个函数。即如何在smarty .tpl文件中调用php函数?

public static function getCategories($id_lang = false, $active = true, $order = true, $sql_filter = '', $sql_sort = '',$sql_limit = '') 
{ 
    if (!Validate::isBool($active)) 
     die(Tools::displayError()); 

    $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' 
     SELECT * 
     FROM `'._DB_PREFIX_.'category` c 
     LEFT JOIN `'._DB_PREFIX_.'category_lang` cl 
     ON c.`id_category` = cl.`id_category` 
     WHERE 1 '.$sql_filter.' '.($id_lang ? 'AND `id_lang` = '.(int)($id_lang) : '').' 
     '.($active ? 'AND `active` = 1' : '').' 
     '.(!$id_lang ? 'GROUP BY c.id_category' : '').' 
     '.($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, c.`position` ASC').' 
     '.($sql_limit != '' ? $sql_limit : '') 
    ); 

    if (!$order) 
     return $result; 

    $categories = array(); 
    foreach ($result AS $row) 
    { 
     $categories[$row['id_parent']][$row['id_category']]['infos'] = $row; 
    } 
    return $categories; 
} 

我想在.tpl文件中调用这个函数。我用{php} {/php}的方式,但这不起作用。 这个叫什么方法?

感谢

+0

这个函数返回一个类别数组,我对吗?好的,那么,你想用这个数组做什么?你需要如何在你的Smarty模板中使用它? –

回答

5

Smarty的是一个模板语言 - 如果你想输出功能的结果,输出分配给一个智者变量

$smarty->assign('categories', getCategories($args)); 

,然后在模板中使用它

{$categories} 

有很少的情况下,这是不正确的模式。

+0

感谢您的回复亚当。我在你上面写了代码。但它不会工作。可以u plz指定我必须写行$ smarty-> assign('categories',getCategories($ args)); – srinu

+0

我同意这条评论。看到一个[在SE上的相关答案](http://stackoverflow.com/a/7446889/913758)。 – NobRuked

+0

@srinu第一行出现在你的php中,第二行出现在你的模板中。你甚至读过手册吗? HTTP://www.smarty。网络/文档 –

4

你可以使用这样的事情,我一直用它

{category.id|function_name} 

让我解释一下:

category.id =是您想要在功能中获取信息的类别的ID

function_name =是功能的名称

+0

这只适用于内置Smarty功能,不适用于问题 –

+0

中定义的自定义功能,它将与自定义功能一起使用, –

+0

我总是这样使用它 函数Test(){ echo“Hello World”; } 在HTML智者我这样使用它后,我包括PHP页面功能 {$ A |测试} 输出将被 的Hello World –

2

因为您使用的是静态方法,您将无法在函数中使用$ this关键字。因此,因此,您将无法使用

$this->context->smarty->assign('categories', self::getCategories($args)); 

所以,你应该创建一个变量和上下文分配给它,并在你的情况,你只需要它的智者的一部分。

$smarty = Context::getContext()->smarty; 

现在你可以使用这个如下:

$smarty->assign('categories', self::getCategories($args)); 

我假设你会打电话给在同一类的功能,所以我用自我:: getCategories($参数) ,如果你想使用它在另一个类使用className :: getCategories($ args)

希望这可以帮助你,试试看,并给我反馈! ;)