# **Chapter 6: Building Your First Webpage - Single Front File + Master File**
> **File Extension Reference:**
> - Gate Files: `*.gate.php` (e.g., `Index.gate.php`)
> - Front Files: `*.front` (e.g., `index_main.front`)
> - Master Files: `*.mast.php` (e.g., `default/master.mast.php`)
> - Front Places: `*.place.front` or `*.place.php`
> **Try it:** This chapter's pieces are all tested:
> `http://localhost/SartajPhpDoc/ex05master.html` (custom master + Front Place,
> `masters/examples/ex05.mast.php`) and `http://localhost/SartajPhpDoc/ex06comp.html`
> (form Components + fusion validation). The default master used by most gates is
> `masters/default/master.mast.php`.
---
## **6.1 The Page Building Blocks**
Before building pages, let's understand the structure:
1. **Gate Class** - Handles logic, events, and data
2. **Front File** (`.front`) - Contains page content (HTML with SartajPhp attributes)
3. **Master File** (`.mast.php`) - Contains page layout (header, footer, menus)
The flow:
```
Gate → FrontFile → MasterFile → Browser
```
## **6.2 Step 1: Register Your Gate**
First, register your Gate in `reg.php`:
```php
<?php
// reg.php
// Register the main application
registerGate("index", __DIR__ . "/apps/Index.gate.php");
```
## **6.3 Step 2: Create the Gate Class**
Create `apps/Index.gate.php`:
```php
<?php
// apps/Index.gate.php
use Sphp\Gates\BasicGate;
use Sphp\Tools\FrontFile;
class Index extends BasicGate
{
private $frtMain;
public function onstart()
{
global $masterf; // set in comp.php, e.g. "masters/default/master.mast.php"
// Create FrontFile object
// Front file name = Gate name + "_" + filename + ".front" (apps/fronts/)
$this->frtMain = new FrontFile("main");
$this->setMasterFile($masterf);
}
public function page_new()
{
// Set the FrontFile to render
$this->setFrontFile($this->frtMain);
}
}
```
## **6.4 Step 3: Create the Front File**
Create `apps/fronts/index_main.front`:
```html
<!-- index_main.front - Page Content -->
<!-- Page Title (becomes component) -->
<title id="pageTitle" runat="server">Welcome</title>
<!-- Page Content -->
<div class="container">
<h1>Welcome to My Website</h1>
<p>This is the main content of the page.</p>
<!-- Dynamic content from database -->
<div id="divContent" runat="server">
<p>Loading content...</p>
</div>
<!-- Link to another page (build URLs with helpers — the app may run in a subfolder) -->
<p>
<a href="##{getGateUrl('index','about')}#">About Us</a> |
<a href="##{getGateUrl('index','contact')}#">Contact</a>
</p>
</div>
```
This is valid HTML that can be opened in any browser!
## **6.5 Step 4: Create the Master File**
Create `masters/default/master.mast.php` (this is the tested project master):
```php
<?php
/* Add menu.php file as Front Place in section "left" */
addFrontPlace("menu", __DIR__ . "/menu.place.php", "left");
/* Run Front Place in section "left" before SartajPHP header HTML Output */
runFrontPlace("menu", "left");
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php
/* Add SartajPHP Managed Bootstrap CSS Library */
SphpBase::SphpJsM()::addBootStrap();
/* Print All SartajPHP Header generated Required */
echo SphpBase::sphpApi()->getHeaderHTML();
?>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col panel">
<div class="row">
<div class="col">
<h2 class="heading" style="font-size:36px;"><?php echo $cmpName; ?></h2>
</div>
</div>
<div class="row">
<div class="col">
<?php
/* Print Front Place "menu" Output */
renderFrontPlace("menu", "left");
?>
</div>
</div>
<div class="row">
<div class="col">
<?php
/* Print SartajPHP App generated Output with Front File Output */
SphpBase::getAppOutput();
?>
</div>
</div>
</div>
</div>
</div>
<?php
/* Print All SartajPHP Footer generated Required */
echo SphpBase::sphpApi()->getFooterHTML();
/* Print all errors related output for debug purposes */
echo SphpBase::sphpApi()->traceError(true) . SphpBase::sphpApi()->traceErrorInner(true);
?>
</body>
</html>
```
Key points (all verified in the running app):
- `addFrontPlace(name, file, section)` **registers** the place file;
`runFrontPlace(name, section)` **executes** it; `renderFrontPlace(name, section)`
**prints** its output. Order in the master: add → run → (later) render.
- `SphpBase::getAppOutput()` is where the rendered FrontFile HTML goes.
- `SphpBase::sphpApi()->getHeaderHTML()` / `getFooterHTML()` flush everything added
by `addHeaderCss`, `addHeaderJsCode`, `addFileLink`, `addFileLinkCode`, …
- `SphpBase::SphpJsM()::addBootStrap()` loads the framework-managed Bootstrap.
- `$cmpName` is the project/app name from `comp.php`.
## **6.6 Step 5: Create the Menu (Front Place)**
The tested project menu is `masters/default/menu.place.php` — a class extending the
framework's `BootstrapMenu`, built with `addMenu` / `addMenuLink`:
```php
<?php
/* use bootstrap menu generater file provide by SartajPHP Framework */
include_once(SphpBase::sphpSettings()->uiKitPath . "/bundle/menu/BootstrapMenu.php");
/* Create Class name as same as file name */
class menu extends BootstrapMenu{
public function onstart() {
$this->sphpApi->addMenu("Home", "","fa fa-home","root");
$this->sphpApi->addMenuLink("Home", SphpBase::sphpSettings()->projectUrl,"fa fa-home","Home");
$this->sphpApi->addMenuLink("Contact Us", getEventUrl('contacts','','index'),"fa fa-fw fa-clock-o","Home");
if(SphpBase::page()->getAuthenticateType() == "GUEST"){
$this->sphpApi->addMenuLink("Login", getGateUrl("signin"),"","Home");
}else{
// roles = auth type and/or permission ids (from registerGate permlist)
$this->sphpApi->addMenu("User",'',"fa fa-home","root",false,"ADMIN,MEMBER");
$this->sphpApi->addMenuLink("Users",getGateUrl('mebProfile'),"fa fa-users","User",false,"mebProfile-view");
// ... more links ...
}
}
}
```
A plain HTML place file works too — see the tested
`masters/examples/ex05bar.place.front` (a Bootstrap navbar rendered by the custom
master `masters/examples/ex05.mast.php`):
```html
<nav id="ex05-place-bar" class="navbar navbar-expand-lg navbar-dark bg-secondary mb-3">
<div class="container-fluid">
<span class="navbar-brand">Ex05 Front Place</span>
<div class="navbar-text text-white">
place file: masters/examples/ex05bar.place.front
</div>
</div>
</nav>
```
> **Tested:** a Gate selects a custom master with
> `$this->setMasterFile('masters/examples/ex05.mast.php')` (no `global $masterf`
> needed then). See `apps/examples/Ex05master.gate.php`.
## **6.7 Complete Flow**
Here's what happens when browser requests `index.html`:
```
1. Browser requests: index.html
↓
2. Framework finds registered Gate: "index"
↓
3. Loads: apps/Index.gate.php
↓
4. Creates: new Index() object
↓
5. Fires: onstart()
- Creates FrontFile object
↓
6. Fires: page_new()
- Calls $this->setFrontFile($this->frtMain)
↓
7. Framework processes: index_main.front
- Parses HTML
- Creates Components (runat="server" tags)
- Evaluates expressions
↓
8. Framework merges with: master.mast.php
- Adds header/footer
- Injects menu from menu.place.front
- Puts FrontFile content in <main>
↓
9. Browser receives complete HTML page
```
## **6.8 Adding Dynamic Content**
Let's enhance our example to show dynamic content:
```php
<?php
// apps/Index.gate.php
use Sphp\Gates\BasicGate;
class Index extends BasicGate
{
private $frtMain;
public function onstart()
{
$this->frtMain = new \Sphp\Tools\FrontFile("main");
}
public function onready()
{
// Get dynamic content in onready (after Components created)
$content = $this->getLatestNews();
// Inject into FrontFile Component
$this->frtMain->getComponent("divContent")->setInnerHtml($content);
// Set page title — the Title component renders its INNER HTML into the
// browser title + SEO meta, so change the inner HTML:
$this->frtMain->getComponent("pageTitle")->setInnerHtml("Home - My Website");
}
public function page_new()
{
$this->setFrontFile($this->frtMain);
}
private function getLatestNews()
{
// Simulated database content
$news = [
["title" => "New Product Launch", "date" => "2024-01-15"],
["title" => "Special Offer", "date" => "2024-01-10"],
["title" => "Website Updated", "date" => "2024-01-05"]
];
$html = "<h2>Latest News</h2><ul>";
foreach ($news as $item) {
$html .= "<li><strong>{$item['title']}</strong> - {$item['date']}</li>";
}
$html .= "</ul>";
return $html;
}
}
```
## **6.9 Using Expression Tags in FrontFile**
Add dynamic content directly in FrontFile using expression tags (tested forms):
```html
<!-- index_main.front with expressions -->
<title id="pageTitle" runat="server">##{$parentGate->pageTitle}#</title>
<div class="container">
<h1>##{$parentGate->siteName}#</h1>
<p>Today's date: ##{date('F j, Y')}#</p>
<div id="divContent" runat="server">
<!-- Content set by Gate -->
</div>
<!-- Conditional display -->
#{if $parentGate->getAuthenticateType() != 'GUEST'}#
<p>Welcome back!</p>
#{else}#
<p><a href="##{getGateUrl('signin')}#">Login</a> to access member area.</p>
#{endif}#
<!-- Using ternary for conditional class -->
<div class="alert ##{($parentGate->isAdmin) ? 'alert-danger' : 'alert-info'}#">
##{$parentGate->message}#
</div>
</div>
```
> **Tested SafeEval rules:** expressions run in a sandbox. Use `##{...}#` for
> values, `##{raw:...}#` when the value is HTML, and `#{if ...}# ... #{else}# ...
> #{endif}#` for blocks. Whitelisted helpers include `date`, `intval`, `time`,
> `getGateUrl`, `getEventUrl`, `getThisGateUrl`. PHP casts like `(int)` are NOT
> supported — use `intval(...)` instead. Gate properties/methods are reached via
> `$parentGate->`.
## **6.10 Adding Components for Interactivity**
Add form Components to your FrontFile:
```html
<!-- contact.front -->
<div class="container">
<h1>Contact Us</h1>
<!-- Form Component -->
<form id="contactForm" runat="server" action="##{getThisGateUrl()}#" method="POST">
<div class="mb-3">
<label class="form-label">Name</label>
<input id="txtName" runat="server" type="text"
class="form-control"
fui-setRequired=""
fui-setMinLen="2"
fui-setForm="contactForm">
</div>
<div class="mb-3">
<label class="form-label">Email</label>
<input id="txtEmail" runat="server" type="email"
class="form-control"
fui-setRequired=""
fui-setEmail=""
fui-setForm="contactForm">
</div>
<div class="mb-3">
<label class="form-label">Message</label>
<textarea id="txaMessage" runat="server"
class="form-control" rows="5"
fui-setRequired=""
fui-setMinLen="10"
fui-setForm="contactForm"></textarea>
</div>
<!-- Error display -->
<alert id="formErrors" runat="server" fun-setShowAll=""></alert>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
```
## **6.11 Complete File Structure**
Your project should look like this:
```
myproject/
├── reg.php # Gate registration
├── start.php # Entry point
├── comp.php # Configuration ($masterf, db, ...)
│
├── apps/
│ ├── Index.gate.php # Main Gate
│ │
│ └── fronts/
│ ├── index_main.front # Home page
│ └── index_contact.front # Contact page (Gate name prefix!)
│
└── masters/
└── default/
├── master.mast.php # Main layout
└── menu.place.php # Navigation menu (BootstrapMenu class)
```
> **Tested naming:** `new FrontFile("main")` inside gate `index` loads
> `apps/fronts/index_main.front` — the file name is always
> `{gatename}_{filename}.front`.
## **6.12 Chapter Summary**
1. **Register Gate** in `reg.php` with `registerGate()`
2. **Create Gate class** extending `BasicGate`
3. **Create Front File** (`.front`) with page content
4. **Create Master File** (`.mast.php`) with layout
5. **Create Front Place** (`.place.front`) for reusable sections like menus
6. Use `$this->setFrontFile()` to render FrontFile
7. Use Components (`runat="server"`) for interactivity
8. Use Expression tags (`##{}#`) for dynamic content
## **6.13 What's Next?**
In the next chapter, you'll learn how to use TWO Front Files in one Gate - one for displaying data (Pagination) and one for editing (Form).
---
*Next: Chapter 7 - Two Front Files Pattern*