Skip to content
Hossein Pira edited this page Sep 7, 2023 · 9 revisions

Views

In controllers or functions, you can easily call your theme and display the site template to the user.

For this, we use the view function that was added in version 1.6.6. This function can also send data.

<?php

namespace Monster\App\Controllers;

class HomeController
{
    public function index()
    {
        view("index");
    }
}

When you write such a code, the index.php file will be displayed in the views folder. From . Use to refer to folders.

<?php

namespace Monster\App\Controllers;

class BlogController
{
    public function post()
    {
        view("blog.post");
    }
}

Here the post.php file from the views/blog folder is displayed. Use an array in the view function to send data to the view.

<?php

namespace Monster\App\Controllers;

class BlogController
{
    public function post($id)
    {
        $tags = [
            'php',
            'web',
            'back-end'
        ];

        view("blog.post", [
            'id' => $id,
            'title' => 'what is php?',
            'tags' => $tags
        ]);
    }
}

To display them, just write the key name of the array as a variable.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APIMonster - <?= $title ?></title>
</head>

<body>
    <h1>Title: <?= $title ?></h1>
    <br />
    <h2>Post ID: <?= $id ?></h2>
    <br />
    <h2>Tags:</h2>
    <ul>
        <?php
        foreach ($tags as $tag) {
            echo "<li>$tag</li>";
        }
        ?>
    </ul>
</body>

</html>

Javascript PHP Data

To use php variables in JavaScript, it is enough to set the value of true to the third value of view.

<?php

namespace Monster\App\Controllers;

class AppController
{
    public function post()
    {
        view("about", [
            'name' => 'Hossein',
            'age' => 19
        ], true);
    }
}

And use it in JavaScript. (just type monster before each data)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/public/style.css">
    <title>API Monster</title>
</head>

<body>
    <script>
        alert(monster.name);
        alert(monster.age);
    </script>
</body>

</html>
Clone this wiki locally