# Working with variables

> Define custom variables with types and fallback values on a template, then supply their values when you send.

Custom template variables let you reuse one template across many sends and fill in the per-recipient details at send time. You declare each variable on the template — with a `key`, a `type`, and an optional `fallback_value` — and reference it in the body. When you send, SendPing substitutes the values you supply (falling back to the declared default where you do not).

## Declaring variables

Reference a variable in the `html` (or `text`) body with triple braces, e.g. `{{{PRODUCT}}}`, and declare it in the `variables` array when you [create the template](https://www.sendping.co/docs/api/templates-create). A template may contain up to **50** variables.

**Variable fields**

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `key` | string | Yes | The variable name referenced in the body. We recommend uppercase (e.g. `PRODUCT_NAME`). |
| `type` | string | Yes | Either `string` or `number`. |
| `fallback_value` | string | number | No | Used when you do not supply a value at send time. Must match `type`. If omitted, a value is required on every send. |

**Node.js**

```js
import { SendPing } from 'sendping';

const mb = new SendPing('mb_xxxxxxxxx');

const { data, error } = await mb.templates.create({
  "name": "order-confirmation",
  "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  "variables": [
    { "key": "PRODUCT", "type": "string", "fallback_value": "item" },
    { "key": "PRICE", "type": "number", "fallback_value": 25 }
  ]
});
console.log({ data, error });
```

**Ruby**

```ruby
require "sendping"

SendPing.api_key = "mb_xxxxxxxxx"

SendPing::Templates.create({
  "name": "order-confirmation",
  "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  "variables": [
    {
      "key": "PRODUCT",
      "type": "string",
      "fallback_value": "item"
    },
    {
      "key": "PRICE",
      "type": "number",
      "fallback_value": 25
    }
  ]
})
```

**PHP**

```php
<?php
require 'vendor/autoload.php';

use SendPing\SendPing;

$sendping = SendPing::client('mb_xxxxxxxxx');

$sendping->templates->create([
  'name' => "order-confirmation",
  'html' => "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  'variables' => [
    [
      'key' => "PRODUCT",
      'type' => "string",
      'fallback_value' => "item"
    ],
    [
      'key' => "PRICE",
      'type' => "number",
      'fallback_value' => 25
    ]
  ]
]);
```

**Python**

```python
import sendping

sendping.api_key = "mb_xxxxxxxxx"

sendping.Templates.create({
  "name": "order-confirmation",
  "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  "variables": [
    {
      "key": "PRODUCT",
      "type": "string",
      "fallback_value": "item"
    },
    {
      "key": "PRICE",
      "type": "number",
      "fallback_value": 25
    }
  ]
})
```

**Go**

```go
import "github.com/shekhu10/sendping-sdks/sendping-go"

client := sendping.NewClient("mb_xxxxxxxxx")

template, err := client.Templates.Create(&sendping.CreateTemplateRequest{
    Name: "order-confirmation",
    Html: "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
    Variables: []sendping.TemplateVariableInput{
        {Key: "PRODUCT", Type: "string", FallbackValue: "item"},
        {Key: "PRICE", Type: "number", FallbackValue: 25},
    },
})
```

**Rust**

```rust
use sendping::{CreateTemplateOptions, SendPing, TemplateVariableInput, TemplateVariableType};

let mb = SendPing::new("mb_xxxxxxxxx");

let params = CreateTemplateOptions::new("order-confirmation")
    .with_html("<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>")
    .with_variable(TemplateVariableInput::new("PRODUCT")
        .with_type(TemplateVariableType::String)
        .with_fallback_value(serde_json::json!("item")))
    .with_variable(TemplateVariableInput::new("PRICE")
        .with_type(TemplateVariableType::Number)
        .with_fallback_value(serde_json::json!(25)));
let _template = mb.templates.create(params).await?;
```

**Java**

```java
import co.sendping.SendPing;
import co.sendping.SendPingResponse;
import co.sendping.requests.CreateTemplateRequest;
import co.sendping.requests.TemplateVariable;

SendPing sendping = new SendPing("mb_xxxxxxxxx");

CreateTemplateRequest request = CreateTemplateRequest.builder()
        .name("order-confirmation")
        .html("<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>")
        .variable(TemplateVariable.of("PRODUCT", "string", "item"))
        .variable(TemplateVariable.of("PRICE", "number", 25))
        .build();

SendPingResponse response = sendping.templates().create(request);
```

**.NET**

```csharp
using SendPing;

ISendPing sendping = SendPingClient.Create("mb_xxxxxxxxx");

var resp = await sendping.TemplateCreateAsync(new TemplateCreateOptions
{
    Name = "order-confirmation",
    HtmlBody = "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
    Variables = new List<TemplateVariableInput>
    {
        new()
        {
            Key = "PRODUCT",
            Type = "string",
            FallbackValue = "item",
        },
        new()
        {
            Key = "PRICE",
            Type = "number",
            FallbackValue = 25,
        },
    },
});
```

**cURL**

```bash
curl -X POST 'https://www.sendping.co/api/templates' \
  -H 'Authorization: Bearer mb_xxxxxxxxx' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "order-confirmation",
  "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  "variables": [
    { "key": "PRODUCT", "type": "string", "fallback_value": "item" },
    { "key": "PRICE", "type": "number", "fallback_value": 25 }
  ]
}'
```

**CLI**

```bash
sendping templates create \
  --name 'order-confirmation' \
  --html '<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>' \
  --variables '[{"key":"PRODUCT","type":"string","fallback_value":"item"},{"key":"PRICE","type":"number","fallback_value":25}]'
```

> **Warning:** These names are reserved and cannot be used as a variable `key`: `FIRST_NAME`, `LAST_NAME`, `EMAIL`, `UNSUBSCRIBE_URL`, `contact`, and `this`.

## Fallback values

A fallback value is used whenever you do not pass a value for that variable at send time. If a variable has **no** fallback, you must supply a value on every send or the request is rejected — so set fallbacks for any variable that is not always present.

## Sending with variables

To send with a template, reference the **published** template by `id` and pass a `variables` object. Both [POST /emails](https://www.sendping.co/docs/api/emails-send) and [POST /emails/batch](https://www.sendping.co/docs/api/emails-batch) accept a template.

**Node.js**

```js
import { SendPing } from 'sendping';

const mb = new SendPing('mb_xxxxxxxxx');

const { data, error } = await mb.emails.send({
  "from": "Acme <hello@yourdomain.com>",
  "to": ["delivered@test.sendping.co"],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": { "PRODUCT": "Laptop" }
  }
});
console.log({ data, error });
```

**Ruby**

```ruby
require "sendping"

SendPing.api_key = "mb_xxxxxxxxx"

SendPing::Emails.send({
  "from": "Acme <hello@yourdomain.com>",
  "to": [
    "delivered@test.sendping.co"
  ],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": {
      "PRODUCT": "Laptop"
    }
  }
})
```

**PHP**

```php
<?php
require 'vendor/autoload.php';

use SendPing\SendPing;

$sendping = SendPing::client('mb_xxxxxxxxx');

$sendping->emails->send([
  'from' => "Acme <hello@yourdomain.com>",
  'to' => [
    "delivered@test.sendping.co"
  ],
  'subject' => "Your order",
  'template' => [
    'id' => "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    'variables' => [
      'PRODUCT' => "Laptop"
    ]
  ]
]);
```

**Python**

```python
import sendping

sendping.api_key = "mb_xxxxxxxxx"

sendping.Emails.send({
  "from": "Acme <hello@yourdomain.com>",
  "to": [
    "delivered@test.sendping.co"
  ],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": {
      "PRODUCT": "Laptop"
    }
  }
})
```

**Go**

```go
import "github.com/shekhu10/sendping-sdks/sendping-go"

client := sendping.NewClient("mb_xxxxxxxxx")

sent, err := client.Emails.Send(&sendping.SendEmailRequest{
    From:    "Acme <hello@yourdomain.com>",
    To:      []string{"delivered@test.sendping.co"},
    Subject: "Your order",
    Template: &sendping.TemplateRef{
        Id:        "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
        Variables: map[string]any{"PRODUCT": "Laptop"},
    },
})
```

**Rust**

```rust
use sendping::{SendEmailOptions, SendPing, TemplateRef};

let mb = SendPing::new("mb_xxxxxxxxx");

let params = SendEmailOptions::new(
    "Acme <hello@yourdomain.com>",
    ["delivered@test.sendping.co"],
    "Your order",
)
.with_template(TemplateRef::by_id("f3b9756c-f4f4-44da-bc00-9f7903c8a83f")
        .with_variable("PRODUCT", serde_json::json!("Laptop")));
let _sent = mb.emails.send(params).await?;
```

**Java**

```java
import co.sendping.SendPing;
import co.sendping.SendPingResponse;
import co.sendping.requests.SendEmailRequest;
import co.sendping.requests.TemplateRef;

SendPing sendping = new SendPing("mb_xxxxxxxxx");

SendEmailRequest request = SendEmailRequest.builder()
        .from("Acme <hello@yourdomain.com>")
        .to("delivered@test.sendping.co")
        .subject("Your order")
        .template(TemplateRef.builder()
                .id("f3b9756c-f4f4-44da-bc00-9f7903c8a83f")
                .variable("PRODUCT", "Laptop")
                .build())
        .build();

SendPingResponse response = sendping.emails().send(request);
```

**.NET**

```csharp
using SendPing;

ISendPing sendping = SendPingClient.Create("mb_xxxxxxxxx");

var resp = await sendping.EmailSendAsync(new EmailMessage
{
    From = "Acme <hello@yourdomain.com>",
    To = "delivered@test.sendping.co",
    Subject = "Your order",
    Template = new TemplateReference
    {
        Id = "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
        Variables = new Dictionary<string, object?> { ["PRODUCT"] = "Laptop" },
    },
});
```

**cURL**

```bash
curl -X POST 'https://www.sendping.co/api/emails' \
  -H 'Authorization: Bearer mb_xxxxxxxxx' \
  -H 'Content-Type: application/json' \
  -d '{
  "from": "Acme <hello@yourdomain.com>",
  "to": ["delivered@test.sendping.co"],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": { "PRODUCT": "Laptop" }
  }
}'
```

> **Warning:** When you send a `template`, you cannot also pass `html` or `text` in the same request — doing so returns a `validation_error`. The request’s `from`, `subject`, and `reply_to` override the template’s defaults; if the template sets no default for one of those, you must provide it in the request.

> **Note:** Only a **published** template can be used to send. See [Version history](https://www.sendping.co/docs/templates/version-history) for the draft → publish workflow.
