Welcome Guest, Not a member yet? Register   Sign In
Way to include partial file on layout file
#1

How does one include a partial file on a layout file?

I've read and tried tutorials on Views using $this->renderSection and $this->include. It seems to me that $this->include can only be used on view files NOT under a layout file.

I want to trim down my layout files as much as possible so that a change in certain components common to all layout files can be easily changed and maintained.

Consider the following file structure:

Code:
Views
|>layout
  >partials
   -head.php
  -master.php   

This is the content of head.php:
Code:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

This is the content of master.php:
Code:
<?php $this->include('partials/head.php'); ?>
<title>Site Title</title>
</head>
<body>
<!--Area for dynamic content -->
<?= $this->renderSection("content"); ?>
</body>
</html>

Running the controller in a browser I get 'CodeIgniter\View\Exceptions\ViewException
Invalid file: head.php '

If I move head from partials to the same directory as master.php, I get the same error.  The only way I can make it work is to remove the $this-> and make include a PHP include.

Am I doing something wrong?
Reply
#2

<?= $this->include('path/relative/to/the/Views/directory') ?>
Reply
#3

(01-29-2022, 06:49 PM)iRedds Wrote: <?= $this->include('path/relative/to/the/Views/directory') ?>

In my original post, how am I not relative to the Views directory?


Code:
Views
|>layout
  >partials
   -head.php
  -master.php

From Views the file master.php is in layout, partials is a sub-directory of layout and head.php is in partials.


Before my original post, I tried variations such as


<?php $this->include('../partials/head.php'); ?> <-- partials back in Views
<?php $this->include('./partials/head.php'); ?> <-- same as without './'

I have also tried with and without '.php'

Why would CI see head.php as an invalid file?

If I do `<?php include('./partials/head');` The error generated is `include(partials/header): failed to open stream: No such file or directory` which makes sense.  PHP include requires '.php'.  If I modify it to `<?php include('./partials/head.php');`, the result works as expected and the include is pulled into the resulting syntax.
Reply
#4

<?= $this->include('layout/partials/head'); ?>

No, dots cannot be used.
The include method is not equivalent to the include language construct.
Reply
#5

Now I get it.  Thank you.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB