学习板块,我做错了什么?

问题描述

我已经安装了 composer 并验证它运行正常

在我的控制器中:

//index.PHP
<?PHP
require 'vendor/autoload.PHP';
use League\Plates\Engine;

$templates = new Engine('/templates');

// Render a template
echo $templates->render('layout',[
    'title' => 'Hello World','name' => 'Jonathan'
]);

这是我的布局:

//layout.PHP
<?PHP $this->layout('template',['title' => $title ]) ?>

<p>Hello,<?= $name ?></p>
<?

这是我的模板:

//template.PHP
<html>
<head>
    <title><?= $title ?></title>
</head>
<body>
    <?= $this->section('content') ?>
</body>
</html>

这是我得到的错误

GET /templates/template.PHP - 未捕获的错误:当不在 /home/finsoft2/Documenti/Playground/plates test/templates/template.PHP:6 中的对象上下文中时使用 $this 堆栈跟踪: #0 {主要} 在第 6 行的 /home/finsoft2/Documenti/Playground/plates test/templates/template.PHP 中抛出

解决方法

您提供的代码基本没问题,除了两个小问题:

  • 应该删除 layout.php 中错误的结束标记。
  • 您在 Engine 的构造函数中输入的模板目录是绝对路径。最安全的选择是使用 __DIR__ 预定义常量来引用路径。这将导致: $templates = new Engine(__DIR__.'/templates');

但是您看到当前错误消息的原因在于其他地方:您正在对 /templates/template.php 执行 GET 请求。您应该执行对 index.php 的请求。直接访问模板文件时,模板引擎不存在,解释器不知道如何填充变量。