# Twig Template Patterns for Laravel Integration

> **Standardized patterns and best practices for creating dynamic, reusable Twig templates from Figma components**

## Overview

This guide establishes consistent patterns for converting static HTML components into dynamic Twig templates that integrate seamlessly with the Laravel project architecture. Following these patterns ensures maintainable, reusable components with proper fallbacks and validation.

### Pattern Benefits
- **Consistent API** - Standardized variable structure across components
- **Robust Fallbacks** - Graceful handling of missing data
- **Type Safety** - Proper validation and escaping
- **Maintainability** - Clear, documented patterns for future updates

## Core Template Patterns

### 1. Variable Declaration Pattern

#### Standard Variable Structure
```twig
{# Content Variables #}
{% if title is empty %}
    {% set title = 'Default Title Text' %}
{% endif %}

{% if description is empty %}
    {% set description = 'Default description providing context about the component functionality.' %}
{% endif %}

{# Action Variables #}
{% if button_text is empty %}
    {% set button_text = 'Default Action' %}
{% endif %}

{% if button_link is empty %}
    {% set button_link = '#' %}
{% endif %}

{# Data Structure Variables #}
{% if items is empty %}
    {% set items = [
        {
            'property': 'value',
            'another_property': 'another_value'
        }
    ] %}
{% endif %}
```

#### Variable Validation Pattern
```twig
{# Validate required variables #}
{% if required_variable is not defined %}
    {% set error_message = 'Required variable "required_variable" not provided' %}
    {# Log error or display fallback #}
{% endif %}

{# Type validation #}
{% if items is not iterable %}
    {% set items = [] %}
{% endif %}

{# Value sanitization #}
{% set title = title|trim|slice(0, 100) %}
{% set description = description|trim %}
```

### 2. Content Block Patterns

#### Basic Content Block
```twig
<section class="componentName" {{ attributes|default('') }}>
    {% if title is not empty %}
        <header class="componentHeader">
            <h2 class="componentTitle">{{ title }}</h2>
            {% if subtitle is not empty %}
                <p class="componentSubtitle">{{ subtitle }}</p>
            {% endif %}
        </header>
    {% endif %}

    {% if description is not empty %}
        <div class="componentContent">
            <div class="wysiwyg">
                {{ description|raw }}
            </div>
        </div>
    {% endif %}
</section>
```

#### Advanced Content Block with Meta
```twig
<section class="componentName" aria-labelledby="{{ component_id|default('component') }}-title">
    <div class="wrapper">
        <header class="sectionHeader">
            <div class="headerContent">
                {% if title is not empty %}
                    <h2 id="{{ component_id|default('component') }}-title" class="sectionTitle">
                        {{ title }}
                    </h2>
                {% endif %}

                {% if description is not empty %}
                    <div class="sectionDescription">
                        {{ description|nl2br }}
                    </div>
                {% endif %}
            </div>

            {% if has_action %}
                <div class="headerActions">
                    {% include 'includes/elements/action_button.twig' with {
                        'text': button_text,
                        'link': button_link,
                        'style': button_style|default('primary')
                    } %}
                </div>
            {% endif %}
        </header>
    </div>
</section>
```

### 3. Iterative Content Patterns

#### Simple List Pattern
```twig
{% if items is not empty %}
    <div class="itemsGrid">
        {% for item in items %}
            <article class="itemCard" role="listitem">
                {% if item.title is not empty %}
                    <h3 class="itemTitle">{{ item.title }}</h3>
                {% endif %}

                {% if item.description is not empty %}
                    <p class="itemDescription">{{ item.description }}</p>
                {% endif %}
            </article>
        {% endfor %}
    </div>
{% endif %}
```

#### Complex Step-by-Step Pattern
```twig
{% if steps is not empty %}
    <div class="stepsGrid" role="list" aria-label="{{ steps_label|default('Process steps') }}">
        {% for step in steps %}
            <article class="stepCard" role="listitem">
                {% if step.number is not empty %}
                    <div class="stepNumber" aria-label="Step {{ step.number }}">
                        {{ step.number }}
                    </div>
                {% endif %}

                {% if step.title is not empty %}
                    <h3 class="stepTitle">
                        {% if step.highlight is not empty %}
                            <span class="highlight">{{ step.highlight }}</span>
                            {{ step.title_remainder|default('') }}
                        {% else %}
                            {{ step.title|raw }}
                        {% endif %}
                    </h3>
                {% endif %}

                {% if step.image or step.image_class %}
                    <div class="stepImage {{ step.image_class|default('') }}"
                         aria-label="{{ step.image_alt|default(step.image_class ~ ' illustration') }}">
                        {% if step.image %}
                            <img src="{{ step.image }}"
                                 alt="{{ step.image_alt|default(step.image_class ~ ' illustration') }}" />
                        {% endif %}
                    </div>
                {% endif %}

                {% if step.description is not empty %}
                    <div class="stepDescription">
                        {{ step.description|nl2br }}
                    </div>
                {% endif %}
            </article>
        {% endfor %}
    </div>
{% endif %}
```

### 4. Conditional Rendering Patterns

#### Feature Flag Pattern
```twig
{% if feature_enabled|default(true) %}
    <div class="feature">
        {# Feature content #}
    </div>
{% endif %}
```

#### Progressive Enhancement Pattern
```twig
{# Basic version always rendered #}
<div class="component basic">
    {{ basic_content }}
</div>

{# Enhanced version conditionally rendered #}
{% if enhanced_mode|default(false) %}
    <div class="component enhanced">
        {{ enhanced_content }}
    </div>
{% endif %}
```

#### A/B Testing Pattern
```twig
{% set variant = variant|default('default') %}

{% if variant == 'variant_a' %}
    {% include 'includes/variants/component_variant_a.twig' %}
{% elseif variant == 'variant_b' %}
    {% include 'includes/variants/component_variant_b.twig' %}
{% else %}
    {# Default variant #}
    {% include 'includes/variants/component_default.twig' %}
{% endif %}
```

### 5. Accessibility Patterns

#### ARIA Labeling Pattern
```twig
<section class="component"
         aria-labelledby="{{ component_id }}-title"
         {% if component_description %}aria-describedby="{{ component_id }}-desc"{% endif %}>

    <h2 id="{{ component_id }}-title" class="componentTitle">
        {{ title }}
    </h2>

    {% if component_description %}
        <p id="{{ component_id }}-desc" class="sr-only">
            {{ component_description }}
        </p>
    {% endif %}
</section>
```

#### Interactive Element Pattern
```twig
{% if button_link is not empty %}
    <a href="{{ button_link }}"
       class="ctaButton"
       role="button"
       aria-label="{{ button_aria_label|default(button_text ~ ' - ' ~ title) }}"
       {% if button_target %}target="{{ button_target }}"{% endif %}>
        {{ button_text }}
        {% if button_icon %}
            <i class="{{ button_icon }}" aria-hidden="true"></i>
        {% endif %}
    </a>
{% endif %}
```

#### Focus Management Pattern
```twig
<div class="component"
     {% if focusable %}tabindex="0"{% endif %}
     {% if focus_skip %}data-skip-focus="true"{% endif %}>
    {# Component content #}
</div>
```

### 6. Content Security Patterns

#### Safe HTML Rendering
```twig
{# Safe for user-generated content #}
<div class="userContent">
    {{ user_content|escape }}
</div>

{# Safe for trusted HTML #}
<div class="trustedContent">
    {{ trusted_html|raw }}
</div>

{# Safe for mixed content #}
<div class="mixedContent">
    {{ mixed_content|striptags('<p><strong><em><ul><ol><li>')|raw }}
</div>
```

#### URL Validation Pattern
```twig
{% set safe_url = button_link|trim %}
{% if safe_url starts with 'http' or safe_url starts with '/' or safe_url starts with '#' %}
    <a href="{{ safe_url }}">{{ button_text }}</a>
{% else %}
    <span class="disabled-link">{{ button_text }}</span>
{% endif %}
```

### 7. Component Composition Patterns

#### Nested Component Pattern
```twig
<div class="parentComponent">
    {% for child in children %}
        {% include 'includes/elements/' ~ child.type ~ '.twig' with child.data %}
    {% endfor %}
</div>
```

#### Slot Pattern
```twig
<div class="componentWrapper">
    <header class="componentHeader">
        {% block header_content %}
            {{ default_header }}
        {% endblock %}
    </header>

    <main class="componentMain">
        {% block main_content %}
            {{ main_content }}
        {% endblock %}
    </main>

    {% if has_footer %}
        <footer class="componentFooter">
            {% block footer_content %}
                {{ default_footer }}
            {% endblock %}
        </footer>
    {% endif %}
</div>
```

### 8. Error Handling Patterns

#### Graceful Degradation
```twig
{% try %}
    {% include complex_template with complex_data %}
{% catch %}
    {# Fallback content #}
    <div class="error-fallback">
        <p>{{ fallback_message|default('Content temporarily unavailable') }}</p>
    </div>
{% endtry %}
```

#### Debug Information Pattern
```twig
{% if app.debug %}
    <div class="debug-info">
        <details>
            <summary>Component Debug Info</summary>
            <pre>{{ dump(component_data) }}</pre>
        </details>
    </div>
{% endif %}
```

## Real-World Implementation Examples

### Weight Loss Approach Component
```twig
{% if title is empty %}
    {% set title = 'Our 3 step approach to the weight loss' %}
{% endif %}

{% if description is empty %}
    {% set description = 'We\'re your personal guide to a healthier, more confident you. From expert advice to proven treatments, we\'re here to support every step of your weight loss journey.' %}
{% endif %}

{% if button_text is empty %}
    {% set button_text = 'Check your eligibility' %}
{% endif %}

{% if button_link is empty %}
    {% set button_link = '#eligibility' %}
{% endif %}

{% if steps is empty %}
    {% set steps = [
        {
            'number': 1,
            'title': '<span class="highlight">Clinically proven</span> medication',
            'image_class': 'medication',
            'description': 'Quisque ipsum magna, facilisis finibus justo id, dignissim ultricies dui.'
        },
        {
            'number': 2,
            'title': '<span class="highlight">Dedicated</span> health team',
            'image_class': 'team',
            'description': 'Quisque ipsum magna, facilisis finibus justo id, dignissim ultricies dui.'
        },
        {
            'number': 3,
            'title': '<span class="highlight">Stay on track</span> with our help',
            'image_class': 'tracking',
            'description': 'Quisque ipsum magna, facilisis finibus justo id, dignissim ultricies dui.'
        }
    ] %}
{% endif %}

<section class="weightLossSection" aria-labelledby="approach-title">
    <div class="wrapper">
        <header class="sectionHeader">
            <div class="headerContent">
                <h2 id="approach-title" class="sectionTitle">
                    {{ title }}
                </h2>
                {% if description is not empty %}
                    <p class="sectionDescription">
                        {{ description }}
                    </p>
                {% endif %}
            </div>
            {% if button_text is not empty and button_link is not empty %}
                <a href="{{ button_link }}" class="ctaButton" role="button"
                   aria-label="Check your eligibility for weight loss treatment">
                    {{ button_text }}
                </a>
            {% endif %}
        </header>

        {% if steps is not empty %}
            <div class="stepsGrid" role="list" aria-label="Weight loss approach steps">
                {% for step in steps %}
                    <article class="stepCard" role="listitem">
                        <div class="stepNumber" aria-label="Step {{ step.number }}">
                            {{ step.number }}
                        </div>
                        <h3 class="stepTitle">
                            {{ step.title|raw }}
                        </h3>
                        <div class="stepImage {{ step.image_class }}"
                             aria-label="{{ step.image_class|capitalize }} illustration">
                            {% if step.image %}
                                <img src="{{ step.image }}"
                                     alt="{{ step.image_alt|default(step.image_class ~ ' illustration') }}" />
                            {% endif %}
                        </div>
                        <p class="stepDescription">
                            {{ step.description }}
                        </p>
                    </article>
                {% endfor %}
            </div>
        {% endif %}
    </div>
</section>
```

## Template Testing Patterns

### Component Testing Template
```twig
{# Test with minimal data #}
{% include 'includes/page_blocks/figma_components/component.twig' %}

{# Test with full data #}
{% include 'includes/page_blocks/figma_components/component.twig' with {
    'title': 'Test Title',
    'description': 'Test description with <strong>HTML</strong> content',
    'button_text': 'Test Button',
    'button_link': '/test-link',
    'items': [
        {'title': 'Item 1', 'description': 'Description 1'},
        {'title': 'Item 2', 'description': 'Description 2'}
    ]
} %}

{# Test edge cases #}
{% include 'includes/page_blocks/figma_components/component.twig' with {
    'title': '',
    'items': []
} %}
```

## Performance Considerations

### Efficient Template Patterns
```twig
{# Cache expensive operations #}
{% set processed_items = items|map(i => process_item(i)) %}

{# Lazy load heavy content #}
{% if show_heavy_content|default(false) %}
    {% include 'includes/heavy_component.twig' %}
{% endif %}

{# Minimize variable processing #}
{% set has_items = items is not empty %}
{% if has_items %}
    {# Process items only once #}
{% endif %}
```

---

*These patterns ensure consistent, maintainable, and accessible Twig templates that integrate seamlessly with the Laravel project while providing robust fallbacks and validation.*