All Tutorials

Your One-Stop Destination for Learning and Growth

Getting Started with Yii2: Part 3 - Views

Welcome back to our series on getting started with web application development using the Yii2 framework. In our previous posts, we covered the basics of setting up a new project and building the controller actions for handling user requests. Today, we'll dive into the world of views in Yii2.

What are Views?

Views are the parts of your application that handle the presentation layer. They take the data generated by controllers and convert it into HTML, JSON or other formats for the end user to view. In simple terms, views are responsible for displaying the output that is sent to the browser.

Creating a View

Let's start by creating a new view for our index action in the index controller. Navigate to your project directory and open up the frontend/controllers/SiteController.php file. Add the following code inside the public function actions() method:

public function actions()
{
    return [
        'index' => ['action' => 'index'],
    ];
}

Now, let's create a new view for our index action. In your terminal or command prompt, navigate to the following directory: frontend/views/site. Here, we will create a new file called index.php. This file will define the layout and content of what is displayed when a user visits your website's homepage.

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;

/* @var $this \yii\web\View */
/* @var $model \app\models\LoginForm */

$this->title = 'Home Page';
?>

<div id="content">
    <p>Welcome to the Yii2 Framework!</p>
</div>

This view file starts by importing some useful helpers from the Yii framework, then sets the title of the page. The main content is wrapped in a <div id="content"> tag and contains a simple welcome message.

Rendering a View

To render this new view when a user visits your homepage, update the code for your index action inside SiteController.php:

public function actionIndex()
{
    return $this->render('index');
}

Save the files and restart your application server if it was running during these changes. Now, when you visit your website's homepage, you should see the message "Welcome to the Yii2 Framework!".

In our next post, we'll continue exploring the Yii2 framework by discussing models and how they interact with controllers and views. Stay tuned!

Published July, 2017