> For the complete documentation index, see [llms.txt](https://docs.reorc.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.reorc.com/cn-reorc-help-center/shu-ju-jian-mo/mo-xing/hong.md).

# 宏

在 Jinja 中，宏（Macro）类似于编程语言中的函数。它允许你定义可重用的代码块，接受参数、处理逻辑并返回结果。Jinja 宏常用于 SQL 模型中，以封装转换逻辑，避免重复的 SQL 代码，从而提升可维护性。

在 Recurve 项目中，你可以将宏定义为资产，并在不同模块和多个模型中复用。

## 语法

Jinja 宏通过 `{% macro %}` 和`{% endmacro %}` 语句进行定义。与 Python 函数类似，宏接受参数、处理逻辑并返回结果。

示例如下：

```sql
{% macro filter_by_status(min_amount, status='completed') %}
    select *
    from {{ source('jaffle_shop', 'orders') }}
    where status = '{{ status }}'
    and amount >= {{ min_amount }}
{% endmacro %}
```

上面的代码定义了一个名为 `filter_by_status` 的宏，该宏根据参数`min_amount` 和可选参数 `status`的值，从 `orders` 表中查询所有符合条件的订单记录。

## 定义宏

要定义一个项目级宏，请按照以下步骤操作：

1. 在 Recurve 中打开你的项目，进入 **Library** > **Macro。**
2. 点击 “**新建 + Add New”。**
3. 输入宏的名称、描述和 SQL 代码。

<figure><img src="/files/e0pz0XrBeLtdkRooQedb" alt=""><figcaption></figcaption></figure>

4. 点击 **“创建/Add”。**

新创建的宏将显示在 **Library** 的 **Macro** 部分。

默认情况下，创建的宏是启用状态，可以立即在模型中使用。如果需要停用宏，可以通过关闭 “**启用/ Active**” 选项来禁用它。

## 调用宏

在宏被定义并启用后，你可以在项目中的任何模型中调用它。宏通过 `{{ ... }}` 表达式进行调用。

例如，使用 `filter_by_status` 宏，我们可以进一步筛选出高价值的已完成订单。

<pre class="language-sql"><code class="lang-sql"><strong>with filtered_orders as (
</strong>   {{ filter_by_status(min_amount=50, status='completed') }}
),

enriched_orders as (
   select 
       order_id,
       amount,
       order_date,
       customer_id,
       case when amount > 100 then 'high_value' else 'standard' end as order_tier
   from filtered_orders
)

select * from enriched_orders
</code></pre>

## 编译结果

```sql
with filtered_orders as (
    -- 按照传入的参数取值渲染可重用的代码
    select *
    from {{ source('jaffle_shop', 'orders') }}
    where status = 'completed'
    and amount >= 50
),

enriched_orders as (
   select 
       order_id,
       amount,
       order_date,
       customer_id,
       case when amount > 100 then 'high_value' else 'standard' end as order_tier
   from filtered_orders
)

select * from enriched_orders
```
