View

Rendering HTML from Controllers

The VIEW class found at sirJuni\Framework\View\VIEW is used to render HTML pages with or without context. If we need access to some data in the HTML file, like for example if we have a profile.html page which needs access to username from the database. We can provide this data to the VIEW which renders/includes the html page in the scope of this provided context.

Here is an example

<?php // controllers.php
use sirJuni\Framework\View\VIEW;

class UserController {
    public function index($request) {
        // render the page
        VIEW::init('index.html');
    }
}

How to Render HTML

Before using VIEW to render html pages, we have to tell the VIEW class where it can find all the template files. We do this by set_path method.

If the templates/ directory is in the root directory of the project, we can configure it as

VIEW::set_path(__DIR__ . "\\templates");

It is when the file where the VIEW is being used is also located in the same root directory. If its in a sub-directory we have to change the path accordingly.

After having set the path to Templates/ directory, we can use the init method of the VIEW class to render HTML files.

VIEW::init('profile.html');         // when no context[data] is needed

If we also need data in the html file to render, we can provide all that data in an Associative array and internally, the init method would extract that associative array and make variables whose name is same as that of the key of the value they store.

An example in the code would be

public function index($request) {
    $context = ['name' => 'shoaib'];
    VIEW::init('index.html', $context);
}

In the above code index.html would have access to a variable with name $name and will store the value shoaib.

So in the html file we can do

<h1>Hello, <?= $name; ?></h1>

and the output would be

Hello, shoaib

This is all about the VIEW class.

Last updated