# Twig Templates Guide - UI Bundle

This document explains the structure, usage, and best practices for Twig templates in the UI Bundle.

## Table of Contents

1. [Architecture Overview](#architecture-overview)
2. [Components](#components)
3. [Modules](#modules)
4. [Sections](#sections)
5. [Base Template](#base-template)
6. [Best Practices](#best-practices)
7. [Naming Conventions](#naming-conventions)

---

## Architecture Overview

The templates are organized in a three-tier hierarchy:

```
templates/
├── base.html.twig          # Base HTML structure
├── component/              # Tier 1: Atomic, reusable UI elements
├── module/                 # Tier 2: Feature-specific, composed templates
└── section/                # Tier 3: Layout templates for page sections
```

### Hierarchy and Dependencies

- **Sections** can use **Modules** and **Components**
- **Modules** can use **Components** and other **Modules**
- **Components** are atomic and should not depend on Modules or Sections
- **Base Template** is the foundation that uses Modules and defines the page structure

---

## Components

### Purpose

Components are **atomic, reusable UI elements** that represent the smallest building blocks of the interface. They are pure, self-contained templates with no business logic dependencies.

### Location

```
templates/component/
```

### Characteristics

- **Atomic**: Single responsibility, minimal dependencies
- **Reusable**: Used across different modules and sections
- **Macro-based**: Use Twig macros (`{% macro %}`) for reusability
- **Configuration-driven**: Accept configuration objects/parameters
- **No nesting**: Components should not include other components (except utility components like `data_attributes`)

### Examples

- `button.html.twig` - Button element with various styles
- `title.html.twig` - Title/heading component
- `label.html.twig` - Label element
- `thumbnail.html.twig` - Image thumbnail
- `data_attributes.html.twig` - Utility macro for data attributes

### Usage Pattern

**Component Definition** (using macros):

```twig
{% macro button(button_obj) %}
    {% set button_obj = button_obj|default(null) %}
    {% set button_classes = ['btn']|merge(button_obj.classes|default([])) %}
    {% set button_href = button_obj.href|default(null) %}
    {% set markup = button_href is null ? button_obj.markup|default('span') : button_obj.markup|default('a') %}
    {# ... additional configuration logic ... #}
    <{{ markup }} class="{{ button_classes|join(' ') }}"{% if button_href is not null %} href="{{ button_href }}"{% endif %}>
        {{ button_obj.text }}
    </{{ markup }}>
{% endmacro %}
```

**Component Usage** (in modules or sections):

```twig
{% from "@Ui/component/button.html.twig" import button %}

{{ button({
    type: 'primary',
    size: 'large',
    text: 'Click me',
    href: '/path'
}) }}
```

### Best Practices for Components

1. **Always use macros** for components that need to be called multiple times
2. **Provide sensible defaults** using `|default()` filter
3. **Accept configuration objects** rather than many individual parameters
4. **Keep them pure** - no database queries or complex logic
5. **Use the `@Ui` namespace** when including: `@Ui/component/component_name.html.twig`

---

## Modules

### Purpose

Modules are **feature-specific templates** that represent larger functional units of the interface. They compose multiple components and may include business logic or data processing.

### Location

```
templates/module/
```

### Characteristics

- **Feature-based**: Organized by feature/domain (e.g., `header/`, `footer/`, `breadcrumb/`)
- **Composed**: Can include multiple components and other modules
- **Context-aware**: May process data or handle conditional logic
- **Subdirectory organization**: Related templates grouped in subdirectories
- **Include/Embed**: Use `{% include %}` or `{% embed %}` for composition

### Examples

- `header/header_main.html.twig` - Main header with logo and navigation
- `breadcrumb/breadcrumb.html.twig` - Breadcrumb navigation
- `nav/link_bar.html.twig` - Navigation link bar
- `footer/footer_main.html.twig` - Main footer
- `consent/cookie_banner.html.twig` - Cookie consent banner

### Module Subdirectory Structure

Modules are organized by feature:

```
module/
├── header/
│   ├── header_main.html.twig
│   ├── header_main_v2.html.twig
│   └── menu/
│       ├── knp_menu.html.twig
│       └── raw_menu.html.twig
├── footer/
│   └── footer_main.html.twig
├── nav/
│   ├── link_bar.html.twig
│   └── menu/
│       └── link_bar_raw_menu.html.twig
└── ...
```

### Usage Pattern

**Module Definition**:

```twig
{% set logo_src = logo_src|default(null) %}
{% set logo_path = logo_path|default(null) %}
{% set logo_alt = logo_alt|default(null) %}
{% set menu_obj = menu_obj|default(knp_menu_get('main'))|default(null) %}

<header id="header-main" class="header-main">
    {% if logo_src is not null and logo_path is not null %}
        <a class="header-main-logo" href="{{ logo_path }}">
            <img src="{{ logo_src }}" alt="{{ logo_alt }}">
        </a>
    {% endif %}
    
    {% include "@Ui/module/header/menu/knp_menu.html.twig" %}
</header>
```

**Module Usage** (in base template or sections):

```twig
{% include "@Ui/module/header/header_main.html.twig" with {
    logo_src: asset('logo.svg'),
    logo_path: path('homepage'),
    logo_alt: 'Site Logo',
    menu_obj: knp_menu_get('main')
} only %}
```

### Best Practices for Modules

1. **Organize by feature** - Group related templates in subdirectories
2. **Use `with ... only`** - When including, explicitly pass variables with `only` to prevent variable leakage
3. **Default all variables** - Use `|default()` to provide fallback values
4. **Block-based composition** - Use `{% block %}` for extensibility when using `{% embed %}`
5. **Include vs Embed**:
   - Use `{% include %}` when you want a simple inclusion
   - Use `{% embed %}` when you need to override blocks within the included template

---

## Sections

### Purpose

Sections are **layout templates** that define the structure and organization of page sections. They provide the skeletal structure for content areas and use Twig's `extends` and `block` mechanisms.

### Location

```
templates/section/
```

### Characteristics

- **Layout-focused**: Define structure, not content
- **Extend-based**: Use `{% extends %}` to inherit from base layouts
- **Block-based**: Define blocks that can be overridden
- **Content-agnostic**: Work with any content passed to them
- **Reusable layouts**: Different layout variations for similar content

### Examples

- `dynamic_content/base_layout.html.twig` - Base layout for dynamic content sections
- `dynamic_content/layout_2_cols_ads.html.twig` - Two-column layout with ads
- `dynamic_content/layout_roller.html.twig` - Carousel/slider layout
- `dynamic_content/layout_roller_big.html.twig` - Large carousel/slider layout
- `dynamic_content/layout_grid_simple.html.twig` - Simple grid layout

### Usage Pattern

**Section Definition** (base layout):

```twig
{% set section_markup = is_big_section|default(false) ? 'div' : 'section' %}
{% set section_classes = ['mg-container']|merge(section_classes|default([]))|join(' ') %}

<{{ section_markup }} class="{{ section_classes }}">
    {% block section_title %}
        {% include "@Ui/component/title.html.twig" %}
    {% endblock %}

    {% block section_content '' %}

    {% block section_cta %}
        {# CTA block with default empty content #}
    {% endblock %}
</{{ section_markup }}>
```

**Section Extension** (specific layout):

```twig
{% extends '@Ui/section/dynamic_content/base_layout.html.twig' %}

{% block section_content %}
    <div class="gd-2-cols">
        <div class="left-col">
            {% for item in entities %}
                {% block item '' %}
            {% endfor %}
        </div>
        <div class="right-col">
            {{ jadPosition('atf_desktop') }}
        </div>
    </div>
{% endblock %}
```

**Section Usage** (in pages):

```twig
{% include "@Ui/section/dynamic_content/layout_2_cols_ads.html.twig" with {
    title_text: 'My Section',
    entities: articles,
    section_classes: ['custom-class']
} %}
```

### Best Practices for Sections

1. **Create base layouts** - Start with a base layout that defines common structure
2. **Use semantic blocks** - Name blocks clearly (e.g., `section_title`, `section_content`, `section_cta`)
3. **Default blocks to empty** - Use `{% block name '' %}` to define empty blocks
4. **Allow customization** - Accept classes and configuration through variables
5. **Keep structure flexible** - Don't hardcode content, use blocks and variables

---

## Base Template

### Purpose

The base template (`base.html.twig`) is the **foundation of all pages**. It defines the HTML structure, includes global modules (header, footer), and sets up the page layout.

### Location

```
templates/base.html.twig
```

### Characteristics

- **HTML structure** - Defines `<html>`, `<head>`, `<body>` structure
- **Global blocks** - Defines blocks for meta, scripts, content areas
- **Module integration** - Includes header, footer, breadcrumb modules
- **Layout blocks** - Defines main content areas (left_col, right_col, etc.)

### Key Blocks

**Head Blocks:**
- `{% block meta %}` - Meta tags and SEO (includes nested blocks: `meta_base`, `meta_og`, `metas_og_player`, `meta_fb_others`, `meta_fb_app`, `meta_fb_pages`, `meta_twitter`, `meta_twitter_id`, `meta_image`, `meta_twitter_image`, `metas_twitter_player`)
- `{% block favicon %}` - Favicon links
- `{% block preload %}` - Resource preload tags
- `{% block stylesheets %}` - CSS includes

**Body Blocks:**
- `{% block body %}` - Main body wrapper
- `{% block header %}` - Header module
- `{% block sub_header %}` - Sub-header section
- `{% block link_bar %}` - Navigation link bar
- `{% block masthead %}` - Masthead/header ad position
- `{% block breadcrumb %}` - Breadcrumb module
- `{% block main_content %}` - Main content area
  - `{% block full_content %}` - Full-width content
  - `{% block left_col %}` - Left column wrapper
    - `{% block left_content %}` - Left column content
  - `{% block right_col %}` - Right column wrapper
    - `{% block right_content %}` - Right column content
- `{% block player_footer %}` - Player footer section
- `{% block footer %}` - Footer module
- `{% block footer_ads %}` - Footer ad positions
- `{% block anchors %}` - Anchor elements and ad bait
- `{% block schemaOrg %}` - Schema.org structured data
- `{% block javascripts %}` - JavaScript includes
- `{% block consent %}` - Consent management (cookies, etc.)
- `{% block external_script %}` - External scripts

### Usage

Pages extend the base template:

```twig
{% extends '@Ui/base.html.twig' %}

{% block main_content %}
    {% include "@Ui/section/dynamic_content/layout_2_cols_ads.html.twig" with {
        entities: articles
    } %}
{% endblock %}
```

---

## Best Practices

### General Guidelines

1. **Namespace Usage**
   - Always use `@Ui` namespace when including templates
   - Example: `@Ui/component/button.html.twig`

2. **Variable Defaults**
   - Always provide defaults using `|default()` filter
   - Example: `{% set title = title|default('Default Title') %}`

3. **Variable Scoping**
   - Use `only` when including to prevent variable leakage
   - Example: `{% include "@Ui/module/header.html.twig" with {logo: src} only %}`

4. **Template Organization**
   - Keep components atomic and focused
   - Group related modules in subdirectories
   - Create base layouts for sections

5. **Comments**
   - Document complex logic or configuration requirements
   - Use comments to explain why, not what

### Performance Considerations

1. **Avoid deep nesting** - Keep include chains shallow
2. **Use `only` keyword** - Prevents unnecessary variable passing
3. **Cache blocks** - Use `{% cache %}` for expensive operations when possible

### Accessibility

1. **Semantic HTML** - Use appropriate HTML elements (`<header>`, `<nav>`, `<main>`, etc.)
2. **ARIA attributes** - Include ARIA labels and roles where appropriate
3. **Alt text** - Always provide alt text for images

### Code Examples

**Good Component Pattern:**

```twig
{% macro card(card_obj) %}
    {% set card_obj = card_obj|default({}) %}
    {% set classes = ['card']|merge(card_obj.classes|default([])) %}
    
    <div class="{{ classes|join(' ') }}">
        {% if card_obj.title %}
            <h3>{{ card_obj.title }}</h3>
        {% endif %}
        {% if card_obj.content %}
            <div class="card-content">{{ card_obj.content }}</div>
        {% endif %}
    </div>
{% endmacro %}
```

**Good Module Pattern:**

```twig
{% set config = config|default({}) %}
{% set items = items|default([]) %}

{% if items is not empty %}
    <nav class="navigation-module">
        {% for item in items %}
            {% include "@Ui/component/link.html.twig" with {
                href: item.href,
                text: item.text
            } only %}
        {% endfor %}
    </nav>
{% endif %}
```

**Good Section Pattern:**

```twig
{% extends '@Ui/section/base_layout.html.twig' %}

{% block section_content %}
    <div class="content-wrapper">
        {% for entity in entities|default([]) %}
            {% block item %}
                {# Default item rendering #}
                <div class="item">{{ entity.title }}</div>
            {% endblock %}
        {% endfor %}
    </div>
{% endblock %}
```

---

## Naming Conventions

### Files

- **Components**: `component_name.html.twig` (e.g., `button.html.twig`)
- **Modules**: `module_name.html.twig` or `feature/module_name.html.twig` (e.g., `header_main.html.twig`)
- **Sections**: `layout_name.html.twig` or `feature/layout_name.html.twig` (e.g., `base_layout.html.twig`)

### Variables

- Use **snake_case** for variables: `button_obj`, `logo_src`, `section_classes`
- Use **descriptive names**: `menu_obj` not `menu`, `header_main_logo` not `logo`

### Classes

- Use **BEM-like naming** in templates: `header-main`, `header-main-logo`, `btn-holder`
- Keep class names consistent with SCSS structure

### Blocks

- Use **descriptive block names**: `section_title`, `section_content`, `header_menu`
- Prefix with context when nested: `header_search`, `header_menu`

---

## Summary

| Type | Purpose | Location | Key Feature |
|------|---------|----------|-------------|
| **Component** | Atomic UI elements | `component/` | Macros, reusable |
| **Module** | Feature-specific templates | `module/` | Includes, composed |
| **Section** | Layout templates | `section/` | Extends, block-based |
| **Base** | Page foundation | Root | HTML structure |

Remember:
- **Components** = Building blocks (atoms)
- **Modules** = Features (molecules/organisms)
- **Sections** = Layouts (templates)
- **Base** = Foundation (page structure)

