# Jinja 模板

Jinja 是一个高效、功能强大的模板引擎，广泛用于生成动态内容。它允许在多种基于文本的格式（如 HTML、XML、CSV 或 LaTex）中嵌入编程逻辑。了解更多信息，请参阅：[Jinja 文档](https://jinja.palletsprojects.com/en/3.1.x/) 。

在现代数据工程中，Jinja 因为能够在 SQL 转换中支持变量、逻辑和重用性，已经成为一种流行的选择。

Recurve 支持在 SQL 模型中直接使用 Jinja。

## Jinja 语法

Jinja 的语法与 Python 类似，代码通常位于特定的分隔符标签内，主要包括以下几种：

* **表达式`{{ ... }}：`** 用于输出字符串、引用变量和调用宏。
* **语句`{% ... %}`**：用于控制流（如 `for` 循环和 `if` 语句），也用于定义宏。
* **注释`{# ... #}`**：注释内容，编译时会被忽略。

以下是一些在 Recurve SQL 模型中使用 Jinja 的示例。

**设置变量**

Recurve 支持创建全局变量，这些变量可以在多个模型和数据管道中重复使用。详情请查阅文档：[变量](/cn-reorc-help-center/advanced_usage/bian-liang.md)

{% tabs %}
{% tab title="SQL 模型" %}
在 Jinja 中，您可以按照以下方式定义局部变量：

```sql
-- min_rental_duration = 3, defined in the Variables section

SELECT film_id, title, rental_duration
FROM film
WHERE rental_duration >= {{ var('min_rental_duration') }}
```

{% endtab %}

{% tab title="编译代码" %}

```sql
SELECT film_id, title, rental_duration
FROM film
WHERE rental_duration >= 3
```

{% endtab %}
{% endtabs %}

`if` **语句**

{% tabs %}
{% tab title="SQL 模型" %}
用 `if` 语句来检查条件：

```sql
{% set include_r_rated = true %}

SELECT film_id, title, rating
FROM film
WHERE 1=1 
{% if include_r_rated %}
  AND rating = 'R'
{% else %}
  AND rating != 'R'
{% endif %}
```

{% endtab %}

{% tab title="编译代码" %}

```sql
SELECT film_id, title, rating
FROM film
WHERE 1=1

  AND rating = 'R'
```

{% endtab %}
{% endtabs %}

`for` **循环**

{% tabs %}
{% tab title="SQL 模型" %}
用 `for` 循环来遍历一个列表或字典：

```sql
{% set categories = ['Action', 'Comedy', 'Drama'] %}

SELECT f.film_id, f.title, c.name AS category
FROM film f
JOIN film_category fc ON f.film_id = fc.film_id
JOIN category c ON fc.category_id = c.category_id
WHERE c.name IN (
  {% for category in categories %}
    '{{ category }}'{% if not loop.last %},{% endif %}
  {% endfor %}
)
```

{% endtab %}

{% tab title="编译代码" %}

```sql
SELECT f.film_id, f.title, c.name AS category
FROM film f
JOIN film_category fc ON f.film_id = fc.film_id
JOIN category c ON fc.category_id = c.category_id
WHERE c.name IN ( 
    'Action',
    'Comedy',
    'Drama'
)
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.reorc.com/cn-reorc-help-center/advanced_usage/jinja-mu-ban.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
