簡體   English   中英

如何在smarty .tpl文件中調用php函數?

[英]How to call a php function inside a smarty .tpl file?

您好我已經在.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}方式,但這不起作用。 叫這個的方法是什么?

謝謝

Smarty是一種模板語言 - 如果要輸出函數的結果,請將輸出分配給smarty變量

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

然后在模板中使用它

{$categories}

很少有這種情況不是正確的模式。

你可以使用這樣的東西,我總是使用它

{category.id|function_name}

讓我解釋一下:

category.id =是您希望在函數中獲取信息的類別的ID

function_name =是函數的名稱

因為您使用的是靜態方法,所以您無法在函數中使用$ this關鍵字。 因此,您將無法使用

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

因此,您應該創建一個變量並為其分配上下文,在您的情況下,您只需要它的智能部分。

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

現在你可以使用如下:

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

我假設你將在同一個類中調用該函數,所以我使用self :: getCategories($ args) ,如果你想在另一個類中使用它,請使用className :: getCategories($ args)

希望這可以幫助你,嘗試並給我反饋! ;)

我同意亞當,雖然我認為體現因為給定的體系結構而使用內部的PHP。
還有另一種方法:使用{insert} - http://www.smarty.net/docs/en/language.function.insert.tpl

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM