简体   繁体   English

无法使用Smarty从PHP代码创建TPL函数

[英]Can't create TPL Function from PHP Code using Smarty

I have created a function to run an SQL query, output the data and that seems fine, Problem is I can't do anything with it now since i can't make the output to the templates work. 我创建了一个函数来运行SQL查询,输出数据,这看起来还不错,问题是我现在无法使用它做任何事情,因为我无法使模板的输出正常工作。

PHP Code: PHP代码:

 function getCategories() {
    try {
        foreach($this->pdo->query("SELECT categories.cat_id, categories.cat_name, categories.cat_description FROM categories") as $row) {
            $rows[] = $row;
        }
    } catch(PDOException $e) {
        print "Error!:" . $e->getMessage();
        return false;
    }
    return $rows;
    $smarty = new Smarty();
    $smarty->assign('categories', $rows);
}

Which simply returns this: 只是返回以下内容:

在此处输入图片说明

Replacing return $rows; 替换return $rows; with return $smarty->assign('categories', $rows); return $smarty->assign('categories', $rows); simply renders a blank page. 只是呈现空白页。

I'm using this in the template: {$categories.cat_name} 我在模板中使用此模板: {$categories.cat_name}

Can anyone help me fix this? 谁能帮我解决这个问题?

I'm trying to rewrite a vulnerable crappy forum script using Smarty so it's a base worth trying to develop a script off of. 我正在尝试使用Smarty重写易受攻击的cr脚的论坛脚本,因此这是尝试开发脚本的基础。 It's literally just categories, topics and a login / register system atm that I'm trying to rewrite using Smarty. 我只是想使用Smarty重写类别,主题和登录/注册系统atm。

The problem is that you create a new smarty object, assign it a variable, but doesn't use it to display your template - so this object get lost. 问题是您创建了一个新的smarty对象,为其分配了一个变量,但不使用它来显示模板-因此该对象会丢失。

I suggest to pass the Smarty object to your function like this: 我建议将Smarty对象传递给您的函数,如下所示:

function getCategories(&$smarty) {
    $rows = array();
    if($result = $this->pdo->query("SELECT categories.cat_id, categories.cat_name, categories.cat_description FROM categories")) {
        $rows = $result->fetchAll();
    }
    $smarty->assign('categories', $rows);
}

This way the object reference will be passed to the function - you will be able to assign any vars you want to it without the need of returning it. 这样,对象引用将传递给函数-您将能够为它分配所需的任何变量,而无需返回它。 Just be sure that you send the Smarty object you use to render the template. 只需确保发送用于渲染模板的Smarty对象即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM