# if

Source: https://zotonic.com/docs/1849/if

URI: https://zotonic.com/id/1849

Language: en



Selects an argument depending on a condition.

For example:

```django
{{ value|if:"yes":"no" }}
```

This is a shortcut for using the <a href="/id/doc_template_tag_tag_if" class="doc-reference doc-reference-tag"><code>tag#if</code></a> tag. The same can be expressed as follows:

```django
{% if value %}yes{% else %}no{% endif %}
```

Note that falsy values (0, `false`, `undefined` or empty string) evaluate to false.

In templates, the compiler evaluates the condition once and only evaluates the selected argument. The other argument is not evaluated, so a model lookup in that branch does not run. Both arguments are required; use `undefined` when the false branch should produce no value.

Combine the filter with `as` to reuse the selected value:

```django
{% if show_image|if:m.media[id]:undefined as medium %}
    {{ medium.mime|escape }}
{% endif %}
```

The media model is only queried when `show_image` is true. The block is rendered when the selected value is truthy, and `medium` contains that value.

This lazy evaluation applies to compiled templates. Direct Erlang calls to `filter_if:'if'/4` follow normal Erlang evaluation: all arguments are evaluated before the function is called.

Elaborate examples
------------------

```django
{% with is_i18n|if:r.translation[lang_code].body:r.body as body %}
```

So if `is_i18n` evaluates to true, `body` is assigned to `r.translation[lang_code].body`, else to `r.body`.

```django
{% include "_language_attrs.tpl" id=pid class=(pid==id)|if:"active":"" %}
```

Add parameter `class` to the included template; when `pid` equals `id`, `class` is `"active"`, otherwise an empty string.

License: 

Attribution: 

Related resources: https://zotonic.com/api/agent/related/1849?language=en


## API access

- [API help](<https://zotonic.com/api-help>)
- [OpenAPI specification](<https://zotonic.com/openapi.json>)
- [This resource as JSON](<https://zotonic.com/api/agent/resource/1849?language=en>)
