How to use layouts in Phalcon?

Member

by lily , in category: PHP Frameworks , a year ago

How to use layouts in Phalcon?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 10 months ago

@lily 

In Phalcon, layouts are used to define a common structure for your web pages, such as header, footer, and navigation menus, that can be reused across multiple pages.


To use layouts in Phalcon, you can follow these steps:

  1. Create a layout file: Create a layout file in the app/views/layouts directory with the common HTML structure for your pages. For example, you might create a file called main.volt:
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
    <title><?= $this->getContent("title") ?></title>
</head>
<body>
    <?= $this->getContent() ?>
</body>
</html>


This layout file defines a basic HTML structure with a title tag and a content section.

  1. Create a view file: Create a view file in the app/views directory with the specific content for your page. For example, you might create a file called index.volt:
1
2
3
4
<?php $this->setVar("title", "Home") ?>

<h1>Welcome to my website!</h1>
<p>This is the home page.</p>


This view file sets the page title and includes some content specific to the home page.

  1. Render the view with the layout: In your controller action, use the view service to render the view file with the layout. For example:
1
2
3
4
5
public function indexAction()
{
    $this->view->pick("index");
    $this->view->setTemplateBefore("main");
}


This code sets the view file to be rendered to index.volt and specifies that it should use the main.volt layout file by calling setTemplateBefore().


When you load the home page, Phalcon will render the index.volt view file within the main.volt layout, replacing the content section with the specific content for the home page.