Learning Plates, what am i doing wrong?

297 views Asked by At

I've already installed composer and verified that it's running properly

this in my controller:

//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'
]);

this is my layout:

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

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

this is my template:

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

this the error that i get:

GET /templates/template.php - Uncaught Error: Using $this when not in object context in /home/finsoft2/Documenti/Playground/plates test/templates/template.php:6 Stack trace: #0 {main} thrown in /home/finsoft2/Documenti/Playground/plates test/templates/template.php on line 6

1

There are 1 answers

0
vixducis On

The code you've provided is largely OK, apart from two small issues:

  • The faulty closing tag in layout.php should be removed.
  • The template directory you've entered in the constructor of Engine is an absolute path. The safest option is to use the __DIR__ predefined constant to reference the path. This would result in: $templates = new Engine(__DIR__.'/templates');

But the reason you're seeing the current error message lies somewhere else: you're performing a GET request to /templates/template.php. You should be performing a request to index.php. When accessing the template file directly, the template engine doesn't exist and the interpreter doesn't know how to fill the variables.