Data Files
Data files allow you to separate data-binding logic from your main PHP code.
They are executed within the template context ($this refers to the template instance).
1. Basic Usage
$tpl->addDataFile('data.php');
data.php:
$this->pick('title')->content('Welcome');
2. Multiple Assignments
$this->pick('title')->content('Dashboard');
$this->pick('username')->content('Tamil');
$this->pick('role')->content('Admin');
---
3. Using PHP Logic
$user = ['name' => 'Tamil', 'role' => 'Admin'];
$this->pick('name')->content($user['name']);
$this->pick('role')->content($user['role']);
---
4. Loop Handling Inside Data File
$users = [
['name' => 'John'],
['name' => 'Jane']
];
foreach ($users as $u) {
$item = $this->addLoopItem('users');
$item->pick('name')->content($u['name']);
}
---
5. Nested Layout Interaction
Data files can modify child templates as well.
$admin = $this->slot('content', 'admin');
$admin->pick('title')->content('Admin Panel');
---
6. Include Handling
$header = $this->include('#header', 'header');
$header->pick('username')->content('Tamil');
---
7. Passing External Data (Recommended Pattern)
Main PHP:
$data = ['title' => 'Dashboard'];
$tpl->addDataFile('data.php');
data.php:
$this->pick('title')->content($data['title'] ?? 'Default');
Use variables from parent scope carefully.
---
8. Execution Order
- Data files run before rendering
- They can modify slots, includes, loops
9. Multiple Data Files
$tpl->addDataFile('header.php');
$tpl->addDataFile('content.php');
👉 Executed in order
---10. Common Mistakes
❌ Using undefined variables
❌ Overwriting same element multiple times
❌ Mixing heavy business logic
❌ Assuming execution order incorrectly
---
❌ Overwriting same element multiple times
❌ Mixing heavy business logic
❌ Assuming execution order incorrectly
11. Best Practices
- Keep data files small and focused
- Use them for view logic only
- Avoid database queries inside data files
- Prefer passing prepared data from controller
12. Performance Notes
- Executed on every render
- Avoid heavy loops or computations
13. When to Use Data Files
- Complex page binding
- Reusable view logic
- Separating controller and view concerns
14. When NOT to Use
- Business logic
- Database queries
- Heavy processing
Data files act like a lightweight controller layer inside templates.
Data Store API (Advanced)
set(string $key, mixed $value)
Stores data in current template.
$this->set('title', 'Dashboard');
---
get(string $key, mixed $default = null)
Retrieves data (with parent inheritance).
$title = $this->get('title');
---
share(string $key, mixed $value)
Stores global data accessible across all templates.
$tpl->share('appName', 'My App');