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

# Liquid構文の使用

> Liquidタグ、フィルター、条件文、ループを使用してメール、プッシュ、SMS、アプリ内、Live Activityのコンテンツをパーソナライズ——OneSignalのタグ、プロパティ、カスタムデータ、Data Feedsなどのデータソースによって提供されます。

Liquidは、OneSignalがメール、プッシュ、SMS、アプリ内、Live Activitiesを含むチャネル全体でメッセージをパーソナライズするためにサポートするテンプレート言語です。タグ、フィルター、条件文を使用してメッセージコンテンツを動的にカスタマイズします。

Liquid構文の詳細については、[公式Liquidドキュメント](https://shopify.github.io/liquid/basics/introduction/)を参照してください。

***

## 基本構文

Liquidは2つの主な構文構造を使用します：

1. **出力タグ**：`{{ ... }}` — 変数またはオブジェクトからデータを表示します。
2. **ロジックタグ**：`{% ... %}` — 条件文またはループを実行します。

***

## 条件文

### 演算子

* `==`、`!=`、`>`、`<`、`>=`、`<=`
* `and`、`or`
* `contains`（文字列または配列）

```text liquid theme={null}
{% if true or false and false %}
  This is true.
{% endif %}
```

### `if`、`elsif`、`else`

```text liquid theme={null}
{%- assign userLang = subscription.language -%}
{% if userLang == "es" -%}
Hola {{ first_name }}!
{%- elsif userLang == "fr" -%}
Bonjour {{ first_name }}!
{%- else -%}
Hello {{ first_name }}!
{%- endif %}
```

### `unless`

```text liquid theme={null}
{% unless level == "1" %}
  Great job getting past the first level!
{% endunless %}
```

***

## フィルター

`{{ variable | filter }}`を使用してフィルターを適用し、データの表示方法を調整します。

### `default`

プロパティが空または存在しない場合にデフォルト値を割り当てます。

```text liquid theme={null}
Hello {{ first_name | default: "there" }}.
```

### `date`

dateフィルターは、タイムスタンプを別の日付形式に変換します。この構文の形式は[strftime](https://strftime.net/)と同じです。入力はRubyの[Time.parse](https://ruby-doc.org/stdlib-2.4.1/libdoc/time/rdoc/Time.html)と同じ形式を使用します。

タグを使用して日付をUnixタイムスタンプ（秒単位）として設定します。これにより、Liquid構文のパーソナライゼーションと[時間演算子](./time-operators)を使用したセグメンテーションの両方を使用できます。たとえば、タグは次のようになります：`bill_due : 1687968776`

```text liquid theme={null}
{{ bill_due | date: "%a, %b %d, %y" }}
{{ "now" | date: "%Y-%m-%d %H:%M" }}
```

```text Result theme={null}
Wed, Jun 28, 23
```

```text liquid theme={null}
{{ bill_due | date: "%Y" }}
```

```text Result theme={null}
2023
```

日付フォーマットは、適切にフォーマットされた日付が含まれている場合、文字列で機能します。

```text liquid theme={null}
{{ "March 14, 2016" | date: "%b %d, %y" }}
```

```text Result theme={null}
Mar 14, 16
```

現在の時刻を取得するには、dateフィルターと一緒に特別な単語`now`（または`today`）を渡します。

```text liquid theme={null}
This message was sent at {{ "now" | date: "%Y-%m-%d %H:%M" }}.
```

```text Result theme={null}
This message was sent at 2022-11-02 14:39.
```

<Info>
  現在の時刻は、メッセージが受信者に送信されたときに基づいてメッセージにレンダリングされます。メッセージをテストしている場合、テストメッセージが送信されたときの現在の時刻が表示されます。
</Info>

### `capitalize`

このフィルターは、文字列の最初の文字を大文字にし、残りの文字を小文字に変換します。

```text liquid theme={null}
{{ "my GREAT title" | capitalize }}
```

```text Result theme={null}
My great title
```

### `round`

このフィルターは、数値を最も近い整数に丸めます。引数として数値が渡された場合は、その小数点以下の桁数に丸めます。

```text liquid theme={null}
{{ 1.2 | round }}
  {{ 2.7 | round }}
{{ 183.357 | round: 2 }}
```

```text Result theme={null}
1
3
183.36
```

### `pluralize`

このフィルターは、指定された数値に基づいて文字列の単数形または複数形を返します。数値は整数である必要があり、文字列として提供できます。文字列の単数形と複数形の両方を提供する必要があります。

```text liquid theme={null}
{{ 1 | pluralize: "singular", "plural" }}
{{ 2 | pluralize: "singular", "plural" }}
1 {{ 1 | pluralize: "person", "people" }}
2 {{ 2 | pluralize: "person", "people" }}
2 {{ "2" | pluralize: "person", "people" }}
```

```text Result theme={null}
singular
plural
1 person
2 people
2 people
```

***

## イテレーション

### `for`ループ

コードブロックを繰り返し実行します。`for`ループ内で使用可能な属性の完全なリストについては、[Liquid `for`ループドキュメント](https://shopify.github.io/liquid/tags/iteration/)を参照してください。

```text liquid theme={null}
{% for product in message.custom_data.products %}
  - {{ product.name }}
  {% else %}
    Sorry, we're sold out of all products.
  {% endfor %}
```

```json Request Body theme={null}
{
  "app_id": "YOUR_APP_ID",
  "template_id": "YOUR_TEMPLATE_ID",
  "custom_data": {
    "products": [
      { "name": "Sweater" },
      { "name": "Hat" },
      { "name": "Shirt" }
    ]
  }
}
```

```text Result theme={null}
- Sweater
- Hat
- Shirt

(message.custom_data.productsが空の場合)
申し訳ありませんが、全製品が売り切れです。
```

<Warning>
  強力で柔軟性がありますが、Liquid構文での`for`ループの使用は、特定のまれなケースで通知配信のパフォーマンスを低下させる可能性があります。`for`ループの使用には注意してください。また、いくつかのプッシュチャネルフィールド（`contents`、`headings`、`subtitle`、`apns_alert`、`url`）では`for`ループの使用を防止していることに注意してください。
</Warning>

### `limit`と`offset`

ループを指定された反復回数に制限します。たとえば、メッセージに4つの製品のみを表示する場合、LimitsとOffsetsを使用して表示される製品の数を指定できます。

```text Data theme={null}
great_numbers = [1,2,3,4,5,6]
```

```text liquid theme={null}
{% for number in great_numbers limit:2 %}
  {{ number }}
{% endfor %}
```

```text Result theme={null}
1 2
```

指定されたインデックスでループを開始するには、オフセット値を追加します：

```text Data theme={null}
great_numbers = [1,2,3,4,5,6]
```

```text liquid theme={null}
{% for number in great_numbers limit: 3 %}
  {{ number }}
{% endfor %}

{% for number in great_numbers limit: 3 offset: 3 %}
  {{ number }}
{% endfor %}
```

```text Result theme={null}
1 2 3
4 5 6
```

### `where`

指定されたプロパティ値を持つオブジェクトのみを含む配列を作成します。デフォルトでは、真の値を持つオブジェクトを含みます。

この例では、製品のリストがあり、キッチン製品を別々に表示したいと仮定します。`where`を使用すると、`type`が`kitchen`である製品のみを含む配列を作成できます。

```text Data theme={null}
products = [
  {name:"Vacuum", type:"electronics"},
  {name:"Spatula", type:"kitchen"},
  {name:"Television", type:"electronics"},
  {name:"Garlic press", type:"kitchen"}
]
```

```text liquid theme={null}
All products:
{% for product in products %}
- {{ product.name }}
{% endfor %}

{% assign kitchen_products = products | where: "type", "kitchen" %}

Kitchen products:
{% for product in kitchen_products %}
- {{ product.name }}
{% endfor %}
```

```text Result theme={null}
All products:
  - Vacuum
  - Spatula
  - Television
  - Garlic press

Kitchen products:
- Spatula
- Garlic press
```

***

## 文字列操作

文字列フィルターを適用して、メッセージ内のタグ値またはインライン文字列の表示方法を調整します。

| コマンド            | 説明                                   | 例                                                        | 出力例         |
| --------------- | ------------------------------------ | -------------------------------------------------------- | ----------- |
| `replace`       | 部分文字列を別の文字列に置き換えます。                  | `{{ 'hello world' \| replace: 'world', 'there' }}`       | hello there |
| `capitalize`    | 文字列の最初の文字を大文字にします。                   | `{{ 'hello' \| capitalize }}`                            | Hello       |
| `upcase`        | 文字列を大文字に変換します。                       | `{{ 'hello' \| upcase }}`                                | HELLO       |
| `downcase`      | 文字列を小文字に変換します。                       | `{{ 'HELLO' \| downcase }}`                              | hello       |
| `strip`         | 文字列から先頭と末尾の空白を削除します。                 | `{{ ' hello ' \| strip }}`                               | hello       |
| `strip_html`    | 文字列からすべてのHTMLタグを削除します。               | `{{ '<p>hello</p>' \| strip_html }}`                     | hello       |
| `truncate`      | 文字列を指定された長さに短縮し、必要に応じて省略記号（…）を追加します。 | `{{ 'This is a long sentence' \| truncate: 10 }}`        | This is a…  |
| `truncatewords` | 指定された単語数の後で文字列を切り詰めます。               | `{{ 'This is a long sentence' \| truncatewords: 2 }}`    | This is…    |
| `replace_first` | 部分文字列の最初の出現を置き換えます。                  | `{{ 'hello world' \| replace_first: 'world', 'there' }}` | hello there |
| `prepend`       | 別の文字列の先頭に文字列を追加します。                  | `{{ 'world' \| prepend: 'hello ' }}`                     | hello world |
| `append`        | 文字列の末尾に文字列を追加します。                    | `{{ 'hello' \| append: ' world' }}`                      | hello world |
| `lstrip`        | 文字列から先頭の空白を削除します。                    | `{{ ' hello' \| lstrip }}`                               | hello       |
| `rstrip`        | 文字列から末尾の空白を削除します。                    | `{{ 'hello ' \| rstrip }}`                               | hello       |

***

## FAQ

### 置換が機能しないのはなぜですか？

* アプリ内メッセージはプロパティ置換をサポートしていません。
* 「テストメッセージを送信」を使用する場合、タグ置換は機能しません。
* タグキーは英数字である必要があります。または、\_と-を使用します（ピリオドやスペースは使用できません）。
* 置換はプレビューモードには表示されません。テストするには実際のメッセージを送信してください。

### `default`と`if/else`はどちらを使うべきですか？

変数値のみにフォールバックが必要で、周囲のテキストが変わらない場合は、**`default`フィルター**を使用します。

```text liquid theme={null}
Hello {{ name | default: "there" }}!
```

```text Result (name = "Jon") theme={null}
Hello Jon!
```

```text Result (nameが空の場合) theme={null}
Hello there!
```

周囲のテキスト、句読点、または文の構造も変数の存在に基づいて変更する必要がある場合は、**`if/else`条件ロジック**を使用します。

```text liquid theme={null}
{% if name %}{{ name }}, shop your favorites!{% else %}Shop your favorites!{% endif %}
```

```text Result (name = "Jon") theme={null}
Jon, shop your favorites!
```

```text Result (nameが空の場合) theme={null}
Shop your favorites!
```

<Warning>
  文の構造が変わる場合は`default`を使用しないでください。例えば、`{{ name | default: "Shop your favorites" }}, shop your favorites`は、nameが空の場合に「Shop your favorites, shop your favorites」とレンダリングされます。フォールバックが変数以外も変更する場合は、`if/else`を使用してください。
</Warning>

### 空白と改行を制御するには？

ハイフンを使用します：`{{- ... -}}`、`{%- ... -%}`で周囲の空白をトリミングします。
詳細については、[空白制御](https://shopify.github.io/liquid/basics/whitespace/)を参照してください。

### ユーザー生成コンテンツを処理するには？

ユーザー生成テキストを`{% raw %}`と`{% endraw %}`でラップして、Liquid解析を防止します。["raw"構文](https://shopify.dev/docs/api/liquid/tags/raw)を参照してください。

```json theme={null}
{
  "contents": {
    "en": "{% raw %} Your user-generated content with invalid characters like {{ {% endraw %}"
  }
}
```

***

## 関連ページ

<Columns cols={2}>
  <Card title="メッセージパーソナライゼーション" icon="wand-magic-sparkles" href="./message-personalization">
    Liquid、Data Feeds、カスタムイベントを含むすべてのパーソナライゼーションオプションの概要。
  </Card>

  <Card title="Data Feeds" icon="database" href="./data-feeds">
    送信時にAPIからメッセージにリアルタイムデータを取得します。
  </Card>

  <Card title="タグ" icon="tag" href="./add-user-data-tags">
    セグメンテーションとLiquidパーソナライゼーションのためにユーザーにキーと値のペアを保存します。
  </Card>

  <Card title="テンプレート" icon="file-lines" href="./templates">
    Liquidパーソナライゼーションが組み込まれた再利用可能なメッセージテンプレートを作成します。
  </Card>
</Columns>
