# EasyStream Template Builder Guide
## Overview
The Template Builder is a powerful drag-and-drop interface that allows users to create custom page layouts for their EasyStream installation. Users can visually design templates using pre-built components without writing any code.
## Features
✨ **Drag and Drop Interface** - Intuitive visual builder
🎨 **Pre-built Components** - Video grids, heroes, text blocks, and more
📱 **Responsive Preview** - Test on desktop, tablet, and mobile
💾 **Auto-save** - Never lose your work
📝 **Version History** - Track changes over time
🎯 **Custom Settings** - Configure each component's appearance
🔄 **Template Management** - Create, edit, duplicate, and delete templates
👁️ **Live Preview** - See your changes in real-time
## Installation
### 1. Database Setup
Run the SQL migration to create required tables:
```bash
mysql -u your_user -p your_database < __install/add_template_builder.sql
```
This creates the following tables:
- `db_templatebuilder_templates` - Stores user templates
- `db_templatebuilder_components` - Component library
- `db_templatebuilder_assignments` - Page assignments
- `db_templatebuilder_versions` - Version history
- `db_templatebuilder_user_prefs` - User preferences
### 2. File Structure
The template builder consists of:
```
f_core/f_classes/
└── class.templatebuilder.php # Backend logic
f_templates/tpl_frontend/tpl_builder/
└── tpl_builder_main.tpl # Builder UI
f_templates/tpl_backend/
└── tpl_template_manager.tpl # Template list view
f_scripts/fe/css/builder/
└── builder.css # Builder styles
f_scripts/fe/js/builder/
├── builder-core.js # Main application
├── builder-components.js # Component logic (future)
└── builder-ui.js # UI helpers (future)
f_modules/m_frontend/
└── templatebuilder_ajax.php # AJAX handler
f_modules/m_backend/
└── template_manager.php # Management interface
```
### 3. Include in Navigation
Add a link to the template manager in your user account navigation:
```smarty
My Templates
```
## User Guide
### Creating a New Template
1. Navigate to **My Templates** in your account
2. Click **Create New Template**
3. You'll be taken to the builder interface
### Builder Interface
The builder consists of three main areas:
#### Left Sidebar - Component Library
- **Search**: Find components quickly
- **Categories**: Filter by component type
- **Component List**: Drag components to canvas
#### Center Canvas - Preview Area
- **Toolbar**: Zoom, grid, and view options
- **Device Preview**: Switch between desktop/tablet/mobile
- **Canvas**: Drag and drop components here
#### Right Sidebar - Properties Panel
- **Page Settings**: Template-wide settings
- **Component Settings**: Configure selected components
- **Section Settings**: Adjust section layout
### Adding Components
1. Find a component in the left sidebar
2. Drag it onto the canvas
3. Drop it where you want it
4. Configure its settings in the right sidebar
### Component Types
#### Video Grid (4 Columns)
Displays videos in a responsive grid layout.
**Settings:**
- Columns (1-6)
- Gap between items
- Padding
#### Hero Banner
Large banner with background image and call-to-action.
**Settings:**
- Background image
- Title and subtitle
- Button text and link
- Overlay opacity
- Height
#### Video Horizontal List
Scrollable horizontal list of videos.
**Settings:**
- Section title
- Gap between items
- Padding
#### Sidebar Widget
Customizable sidebar container.
**Settings:**
- Widget title
- Background color
- Padding and border radius
#### Text Block
Rich text content with heading.
**Settings:**
- Heading text and size
- Content
- Text alignment
- Colors and spacing
#### Image Block
Image with optional caption.
**Settings:**
- Image URL
- Alt text
- Caption
- Alignment
- Max width
#### Custom HTML
Advanced users can add custom HTML/Smarty code.
**Settings:**
- HTML content
- Padding
### Sections
Components are organized into **sections**. Each section can have:
- **Multiple columns** (1-4)
- **Custom gap** between columns
- **Background color**
- **Padding** (top, right, bottom, left)
### Editing Components
1. Click on a component in the canvas
2. The right sidebar shows its settings
3. Modify any setting
4. Changes apply immediately
### Moving Components
- **Drag and drop** within sections
- Use **section controls** to move sections up/down
- **Duplicate** components or sections
- **Delete** unwanted elements
### Responsive Design
Click the device icons in the header to preview:
- 🖥️ **Desktop** (full width)
- 📱 **Tablet** (768px)
- 📱 **Mobile** (375px)
### Saving Templates
- **Auto-save**: Automatically saves every 3 seconds
- **Manual save**: Click "Save" button
- **Versioning**: Each save creates a version history entry
### Publishing Templates
1. Click **Publish** when ready
2. Sets the template as active
3. Template becomes available for use
## Developer Guide
### Creating Custom Components
Add components to the database:
```sql
INSERT INTO `db_templatebuilder_components`
(`component_name`, `component_slug`, `component_category`, `component_html`,
`component_css`, `component_settings_schema`, `is_system`, `description`)
VALUES
('My Component', 'my_component', 'custom',
'
{{content}}
',
'.my-component { padding: {{padding}}px; }',
'{"content": {"type": "textarea", "default": "Hello"}, "padding": {"type": "number", "default": 20}}',
1,
'Custom component description');
```
### Component Settings Schema
The `component_settings_schema` is a JSON object defining configurable settings:
```json
{
"setting_name": {
"type": "number|text|textarea|color|boolean|select|image|code",
"default": "default_value",
"min": 0,
"max": 100,
"step": 5,
"options": ["option1", "option2"]
}
}
```
**Supported Types:**
- `number` - Numeric input with optional min/max/step
- `text` - Single line text
- `textarea` - Multi-line text
- `color` - Color picker
- `boolean` - Checkbox
- `select` - Dropdown with options
- `image` - Image URL input
- `code` - Code editor
### Template Variables
Component HTML can use placeholders:
```html
```
Placeholders are replaced with:
1. Component settings values
2. Global data passed to renderer
### Rendering Templates
#### PHP
```php
$templateBuilder = new VTemplateBuilder();
// Render by ID
$html = $templateBuilder->renderTemplate(123);
// Render by slug
$html = $templateBuilder->renderTemplate('my-template-slug');
// Render with data
$html = $templateBuilder->renderTemplate(123, [
'video_items' => $videos,
'user_name' => $userName
]);
echo $html;
```
#### Smarty Template
```smarty
{* Include template builder output *}
{$template_html}
```
### AJAX API
All AJAX requests go to `/f_modules/m_frontend/templatebuilder_ajax.php`
**Get Components:**
```javascript
GET /templatebuilder_ajax.php?action=get_components
GET /templatebuilder_ajax.php?action=get_components&category=video_grid
```
**Create Template:**
```javascript
POST /templatebuilder_ajax.php
{
"action": "create_template",
"template_name": "My Template",
"template_type": "homepage",
"template_structure": "{...}"
}
```
**Update Template:**
```javascript
POST /templatebuilder_ajax.php
{
"action": "update_template",
"template_id": 123,
"template_structure": "{...}",
"change_note": "Updated hero section"
}
```
**Get Template:**
```javascript
GET /templatebuilder_ajax.php?action=get_template&template_id=123
```
**Preview Template:**
```javascript
GET /templatebuilder_ajax.php?action=preview&template_id=123
```
### Template Structure Format
Templates are stored as JSON:
```json
{
"sections": [
{
"id": "section-1",
"columns": 1,
"gap": 20,
"styles": {
"background_color": "#f5f5f5",
"padding": "40px 20px"
},
"blocks": [
{
"id": "block-1",
"component": "hero_banner",
"settings": {
"title": "Welcome",
"subtitle": "To my site",
"height": 400,
"overlay_opacity": 0.5
}
}
]
}
],
"layout_type": "flex",
"max_width": 1200
}
```
### Extending the Builder
#### Add New Component Category
1. Update SQL insert in `add_template_builder.sql`
2. Add category button in `tpl_builder_main.tpl`
3. Add icon mapping in `builder-core.js` `getCategoryIcon()`
#### Custom CSS for Components
Add component-specific CSS in the component definition:
```css
.component-custom {
/* Your styles */
padding: {{padding}}px;
color: {{text_color}};
}
```
Variables are replaced during rendering.
#### Custom JavaScript
Advanced components can include JavaScript:
```javascript
// In component's custom_js field
document.querySelectorAll('.my-component').forEach(el => {
el.addEventListener('click', () => {
console.log('Clicked!');
});
});
```
### Security Considerations
1. **Input Validation**: All user input is sanitized via `VDatabase::sanitizeInput()`
2. **Ownership Verification**: Users can only edit their own templates
3. **HTML Sanitization**: Custom HTML should be sanitized before rendering
4. **XSS Prevention**: Use Smarty's `|escape` modifier for user content
5. **SQL Injection**: All queries use prepared statements via VDatabase
### Performance Optimization
1. **Caching**: Rendered templates can be cached
2. **Lazy Loading**: Load components on demand
3. **Minification**: Minify CSS/JS before production
4. **Database Indexes**: Indexes already added for performance
5. **JSON Validation**: Validate structure before saving
## Keyboard Shortcuts
- **Ctrl/Cmd + S** - Save template
- **Ctrl/Cmd + Z** - Undo
- **Ctrl/Cmd + Shift + Z** - Redo
- **Delete** - Delete selected element
- **Esc** - Deselect element
## Troubleshooting
### Components Not Loading
Check:
1. Database has component records
2. AJAX endpoint is accessible
3. JavaScript console for errors
### Template Not Saving
Check:
1. User is logged in
2. Template name is provided
3. JSON structure is valid
4. Database connection is active
### Preview Not Working
Check:
1. Template is saved first
2. Template ID is correct
3. Rendering logic has no errors
### Styles Not Applying
Check:
1. CSS files are loaded
2. Builder CSS path is correct
3. Theme compatibility
## Best Practices
### For Users
1. **Name templates clearly** - Use descriptive names
2. **Save regularly** - Use auto-save but manually save major changes
3. **Test responsiveness** - Check all device sizes
4. **Use sections wisely** - Group related content
5. **Keep it simple** - Don't overcomplicate layouts
### For Developers
1. **Component reusability** - Create flexible components
2. **Settings validation** - Validate all settings in schema
3. **Documentation** - Document custom components
4. **Testing** - Test templates on different browsers
5. **Version control** - Use version history for major changes
## API Reference
### VTemplateBuilder Class
#### Methods
**`createTemplate($data)`**
- Creates new template
- Returns: `['success' => bool, 'template_id' => int, 'slug' => string]`
**`updateTemplate($template_id, $data, $change_note = null)`**
- Updates existing template
- Returns: `['success' => bool]`
**`deleteTemplate($template_id)`**
- Deletes template
- Returns: `['success' => bool]`
**`getTemplate($template_id, $check_ownership = true)`**
- Gets template by ID
- Returns: `array|null`
**`getTemplateBySlug($slug)`**
- Gets template by slug
- Returns: `array|null`
**`getUserTemplates($filters = [])`**
- Gets all user templates
- Returns: `array`
**`renderTemplate($template_identifier, $data = [])`**
- Renders template HTML
- Returns: `string`
**`getComponents($category = null)`**
- Gets available components
- Returns: `array`
**`duplicateTemplate($template_id, $new_name = null)`**
- Duplicates template
- Returns: `['success' => bool, 'template_id' => int]`
## Support
For issues or questions:
1. Check this documentation
2. Review code comments
3. Check database logs via `VLogger`
4. Inspect browser console
5. Review version history for changes
## Future Enhancements
Potential improvements:
- [ ] Template marketplace/sharing
- [ ] More component types
- [ ] Advanced grid system
- [ ] Animation options
- [ ] A/B testing support
- [ ] Template import/export
- [ ] Collaboration features
- [ ] Mobile app builder
- [ ] Component library expansion
- [ ] AI-powered suggestions
## Credits
Built for EasyStream by the EasyStream team.
## License
Same license as EasyStream platform.
---
**Last Updated:** 2025-01-22
**Version:** 1.0.0