> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hooked.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Scenes & Variables

> Master the template system with scenes and variable replacement

## Overview

Templates in Hooked use a powerful **scene-based** system that allows you to create personalized videos at scale. Understanding scenes and variables is key to leveraging templates effectively.

## What are Scenes?

Scenes are individual segments of your video, each with its own script and customizable overlay elements. Think of them as slides or sections in your video presentation.

### Scene Structure

```json theme={null}
{
  "script": "Hello! Welcome to our presentation.",
  "variables": [
    { "key": "name", "value": "John Doe" },
    { "key": "company", "value": "Acme Corp" },
    { "key": "title", "value": "Marketing Director" }
  ]
}
```

Each scene contains:

* **script**: The narration text that the avatar will speak
* **variables**: Array of key-value pairs for text overlays displayed on the slide (names, titles, company names, etc.)

## What are Variables?

Variables are dynamic text elements that appear as overlays on your video slides. They allow you to personalize each video by replacing placeholder text with specific values.

**Common uses:**

* Names and titles
* Company names
* Product information
* Dates and numbers
* Custom messages

### Variable Names

**✅ Valid Variable Names:**

```
name
first_name
customer_id
subscription_plan
trial_days
product_name
company
title
```

**Rules:**

* Lowercase letters
* Use underscores for spaces
* Descriptive names
* No special characters

**❌ Invalid Variable Names:**

```
Name              // Capital letters
first name        // Spaces
customer-id       // Hyphens
1st_customer      // Starts with number
special!char      // Special characters
```

## Creating Multi-Scene Templates

Templates can have multiple scenes, each with different overlay text:

```javascript theme={null}
const scenes = [
  {
    // Scene 1: Introduction slide
    script: "Hello! Thank you for joining our platform.",
    variables: [
      { key: 'name', value: 'Sarah Johnson' },
      { key: 'company', value: 'TechStart Inc' },
      { key: 'title', value: 'Marketing Director' }
    ]
  },
  {
    // Scene 2: Product information slide
    script: "Let me tell you about our product features and pricing.",
    variables: [
      { key: 'plan_name', value: 'Professional Plan' },
      { key: 'price', value: '$99/month' },
      { key: 'features', value: 'Unlimited videos, Priority support' }
    ]
  },
  {
    // Scene 3: Call to action slide
    script: "Ready to get started? Let's connect!",
    variables: [
      { key: 'website', value: 'www.techstart.com' },
      { key: 'email', value: 'sarah@techstart.com' },
      { key: 'phone', value: '+1 (555) 123-4567' }
    ]
  }
];
```

## Variable Rules

### 1. Template Defines Required Variables

The template creator defines which variables are needed for each scene. When generating a video, you must provide values for all required variables.

```javascript theme={null}
// ❌ Will fail - template requires 'company' but it's missing
{
  script: "Welcome to our presentation!",
  variables: [
    { key: 'name', value: 'John' }
    // Missing 'company' variable that the template expects
  ]
}

// ✅ Correct - all required variables provided
{
  script: "Welcome to our presentation!",
  variables: [
    { key: 'name', value: 'John Doe' },
    { key: 'company', value: 'Acme Corp' },
    { key: 'title', value: 'Sales Director' }
  ]
}
```

### 2. Variables Are Case-Sensitive

Variable names must match exactly:

```javascript theme={null}
// ❌ Wrong - case mismatch
{
  variables: [
    { key: 'name', value: 'John' }  // lowercase 'name'
  ]
}
// But template expects 'Name' (capital N)

// ✅ Correct - exact match
{
  variables: [
    { key: 'Name', value: 'John' }  // matches template's 'Name'
  ]
}
```

### 3. Variables Appear as Text Overlays

Variables are displayed as text elements on the slide, not spoken in the narration:

```javascript theme={null}
{
  // This is what the avatar says
  script: "Let me introduce our featured product.",
  
  // These appear as text on the slide
  variables: [
    { key: 'product_name', value: 'Pro Analytics Dashboard' },
    { key: 'price', value: '$99/month' },
    { key: 'tagline', value: 'Data-driven decisions made easy' }
  ]
}
```

### 4. Empty Values Are Allowed

Variables can have empty strings if the template allows it:

```javascript theme={null}
{
  script: "Here's our contact information.",
  variables: [
    { key: 'phone', value: '' },  // Empty if not available
    { key: 'email', value: 'contact@company.com' },
    { key: 'website', value: 'www.company.com' }
  ]
}
```

## Complete Example

Here's a full example of generating a video from a template with multiple scenes:

```javascript theme={null}
const videoRequest = {
  type: "class",
  templateId: "template_abc123",
  title: "Onboarding Video for Sarah",
  aspectRatio: "ratio_16_9",
  caption: {
    enabled: true,
    preset: "wrap1",
    alignment: "bottom"
  },
  scenes: [
    {
      script: "Welcome to {{company}}, {{name}}!",
      variables: [
        { key: "company", value: "TechStart" },
        { key: "name", value: "Sarah" }
      ]
    },
    {
      script: "You're on the {{plan}} plan with {{feature_count}} features.",
      variables: [
        { key: "plan", value: "Professional" },
        { key: "feature_count", value: "50+" }
      ]
    },
    {
      script: "Your account manager is {{manager}}. Reach out at {{email}}!",
      variables: [
        { key: "manager", value: "Mike Chen" },
        { key: "email", value: "mike@techstart.com" }
      ]
    }
  ],
  webhook: "https://myapp.com/webhook?user=sarah"
};

// Make API request
const response = await fetch('https://api.hooked.so/v1/project/create', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': process.env.HOOKED_API_KEY
  },
  body: JSON.stringify(videoRequest)
});

const result = await response.json();
console.log('Project ID:', result.data.projectId);
```

## Best Practices

### Use Descriptive Variable Names

```javascript theme={null}
// ❌ Bad - unclear
{{x}}, {{val}}, {{a}}

// ✅ Good - self-documenting
{{customer_name}}, {{product_price}}, {{discount_percentage}}
```

### Keep Scripts Natural

```javascript theme={null}
// ❌ Awkward - too many variables close together
"Hi {{title}} {{first_name}} {{last_name}} from {{company_name}} in {{city}}, {{state}}!"

// ✅ Natural - well-spaced
"Hi {{name}}! I see you're from {{company}} in {{location}}."
```

### Validate Before Sending

Always check that:

1. All required variables are present
2. Variable names match exactly (case-sensitive)
3. Values are properly formatted (strings, numbers, etc.)
4. No extra variables are provided that don't exist in the script

```javascript theme={null}
function validateScene(scene) {
  // Extract variables from script
  const scriptVars = [...scene.script.matchAll(/\{\{(\w+)\}\}/g)]
    .map(match => match[1]);
  
  // Get provided variable keys
  const providedKeys = scene.variables.map(v => v.key);
  
  // Check for missing variables
  const missing = scriptVars.filter(v => !providedKeys.includes(v));
  if (missing.length > 0) {
    throw new Error(`Missing variables: ${missing.join(', ')}`);
  }
  
  return true;
}

// Usage
try {
  validateScene(myScene);
  // Proceed with API call
} catch (error) {
  console.error('Validation failed:', error.message);
}
```

## Common Patterns

### Personalized Greeting

```javascript theme={null}
{
  script: "Hi {{first_name}}! Great to see you again.",
  variables: [
    { key: "first_name", value: "Sarah" }
  ]
}
```

### Product Information

```javascript theme={null}
{
  script: "The {{product_name}} costs {{price}} and includes {{features}}.",
  variables: [
    { key: "product_name", value: "Pro Plan" },
    { key: "price", value: "$99/month" },
    { key: "features", value: "unlimited videos and priority support" }
  ]
}
```

### Call to Action

```javascript theme={null}
{
  script: "Ready to get started? Visit {{website}} or call {{phone}}.",
  variables: [
    { key: "website", value: "www.yoursite.com" },
    { key: "phone", value: "1-800-555-0123" }
  ]
}
```

## Troubleshooting

### Error: "Variable not found in script"

**Problem:** You provided a variable that doesn't exist in the script.

**Solution:** Remove unused variables or add them to the script.

```javascript theme={null}
// ❌ Error - 'age' variable not in script
{
  script: "Hello {{name}}!",
  variables: [
    { key: "name", value: "John" },
    { key: "age", value: "30" }  // Not used
  ]
}

// ✅ Fixed
{
  script: "Hello {{name}}!",
  variables: [
    { key: "name", value: "John" }
  ]
}
```

### Error: "Missing required variable"

**Problem:** A `{{variable}}` in the script doesn't have a value.

**Solution:** Provide all required variables.

```javascript theme={null}
// ❌ Error - missing 'company'
{
  script: "Hello {{name}} from {{company}}!",
  variables: [
    { key: "name", value: "John" }
  ]
}

// ✅ Fixed
{
  script: "Hello {{name}} from {{company}}!",
  variables: [
    { key: "name", value: "John" },
    { key: "company", value: "Acme Corp" }
  ]
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Complete Workflow" icon="diagram-project" href="/guides/complete-workflow">
    See scenes and variables in action
  </Card>

  <Card title="Personalization" icon="sparkles" href="/guides/personalization">
    Advanced variable strategies
  </Card>

  <Card title="Bulk Generation" icon="layer-group" href="/guides/bulk-generation">
    Generate at scale with templates
  </Card>

  <Card title="Template Example" icon="code" href="/examples/template-personalization">
    Complete code example
  </Card>
</CardGroup>
