Thursday 21 March 2019

Yii views and layouts

Within Yii we have the concept of views and layouts. This can get a little confusing for 2 reasons:

  1. They both reside within the views directory
  2. The higher level is the layout, which lies within a sub directory if views i.e views/layouts

That aside once you strip the garbage found in most tutorial the concept is straight forward.
Let's take a layout as our starting position. In this case views/layouts/main.php
This contains 3 elements which are particular to Yii.

  1. The declaration of a variable from config/web.php to set the language
  2. The declaration of a variable which resides in the view for the title tag
  3. The all important echo of the $content variable which displays the contents of the view

<!DOCTYPE html>
<html lang="<?php echo Yii::$app->language ?>">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $this->title ?></title>
</head>
<body>
<?php echo $content; ?>
</body>
</html>

Now let's look at the views/site/index.php
This view passes the title variable which is used in the <title> tag. of the layout above. "Hello world!" is displayed where $content is echo'd from the layout above.
<?php
$this->title = 'My Yii Application';
?>
Hello world!

No comments:

Post a Comment