php - 如何在PHP Plates模板引擎上显示错误

标签 php templates error-handling

我正在尝试为我的一个项目设置platesphp

该模型中的一种方法将检查新用户提供的电子邮件地址,并告知他们尝试使用的电子邮件是否存在。

就像是

class UserModel extends BaseModel
{
    public $errors = [];

    public function validate()
    {
        if (filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) === false) {
            $this->errors[] = 'Invalid email';
        }
        if ($this->emailExists($this->request->post['email'])) {
            $this->errors[] = 'Email already exist';
        }
    }

    protected function emailExists($email)
    {
        $sql = 'SELECT * FROM user_account WHERE email = :email';
        -----
        -----
        $stmt->execute();
        return $stmt->fetch() !== false;
    }
}

并在 Controller 中
public function register()
{
    $this->load->getModel('UserModel');

    if ($this->model_UserModel->registerUser($this->request->post)) {
        echo "Success ... load (redirect) second page";
    } else {
        $data ['error'] = $this->model_UserModel->errors;
        echo $this->template->render('home/home', $data);
    }
}

如果电子邮件存在,并且我var dump $ data ['error'],则会显示“UserModel中的validate方法中定义的”已经存在电子邮件”。

现在,我试图通过在tpl文件中添加以下行来在主模板上获取错误消息
<?php if (!empty($this->e($errors))): ?>
    <?php foreach($errors as $error): ?>
        <li><?=$this->e($error)?></li>
    <?php endforeach ?>
<?php endif;?>

但是现在如果我单击注册页面,模板会显示

注意: undefined variable :第14行中的C:\ xampp \ htdocs \ vem \ App \ Views \ template \ register \ registeruser.tpl中的错误

我该如何前进?

我什至尝试设置$this->e($error) = '',但是naa显示了另一个错误。

最佳答案

在 Controller 上,您正在设置变量error,但是在模板中,您正在访问变量errors(带有s)。
试试看

<?php if (@$error)): ?>
    <?php foreach($error as $e): ?>
        <li><?=$this->e($e)?></li>
    <?php endforeach ?>
<?php endif;?>

关于php - 如何在PHP Plates模板引擎上显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713290/

相关文章:

php - 删除标签内的空白而不删除\n

PHP - 数组的 URL

html - 跨多个子目录使用 HTML 模板

c++ - 为命名空间中的类模板重载输出运算符

java - Java while循环不适用于字符的输入检查

php opencart 2.1.0.1 mysql查询错误: mysql_num_fields() expects parameter 1 to be resource object given in

php - 如何检测像 Facebook 这样的新机器?

c++ - C++ 中基于类型的模板函数

iis - 如何覆盖 Web API 中的所有标准错误页面

MySQL存储过程回滚的原因