# Twig

The Advanced Views templates by default, utilize the[ Twig engine](https://twig.symfony.com/), a modern and widely adopted template engine.&#x20;

{% hint style="info" %}
You can read why we use it, and compare it with the Blade alternative [here]().
{% endhint %}

## Built-in Twig features

If you're new to Twig, we provide an overview of its key features below.&#x20;

You can launch the snippets and play with them in your browser using the [Twigfiddle](https://twigfiddle.com/) service.&#x20;

{% embed url="https://www.youtube.com/watch?v=50RBUmPOYig" %}

### Variables

Using double curly brackets, you can easily inject variables into your markup. For instance:

```twig
{{ my_variable }}
```

When working with arrays, follow this syntax:

```twig
{{ my_array.my_key }}
```

You can also [define variables](https://twig.symfony.com/doc/3.x/tags/set.html) directly within a template:

```twig
{% set my_var = my_rate * 10 %}
{% set my_var = my_rate ~ " USD" %}
```

### Auto-escaping

With Twig, you don't need to worry about escaping variables anymore because Twig automatically escapes all variables passed into the template by default.&#x20;

However, in some specific cases, you may still need to pass HTML without escaping. For example, when displaying a WYSIWYG field value, you should use the `|raw` filter like this: `{{ my_var|raw }}`. Without the `|raw` filter, HTML tags will be converted into HTML entities and displayed on the page as plain text.

### Math

Twig allows you to perform any mathematical operations within brackets. For example:

```twig
{{ 5 + 10 }}
```

This will output 15.

### Conditions

You can create different markup based on [various conditions](https://twig.symfony.com/doc/2.x/tags/if.html). For instance:

```twig
{% if my_variable == 'some_value' %}
    <div> Markup if the condition is met </div>
{% else %}
    <div> Markup if the condition is not met </div>
{% endif %}
```

The 'else' part is optional.

You can also use [odd](https://twig.symfony.com/doc/3.x/tests/odd.html) and [even](https://twig.symfony.com/doc/3.x/tests/even.html) for comparison, such as:

```twig
{% if my_var is odd %}
    <div> Markup for odd values </div>
{% endif %}
```

### Loop

Twig provides a straightforward way to [iterate through arrays](https://twig.symfony.com/doc/2.x/tags/for.html):

```twig
{% for item in my_array %}
    <div>{{ item }}</div>
{% endfor %}
```

Additionally, you can access the current index using the `loop.index` magic variable, which starts at "1". This can be useful for detecting the first element or distinguishing between odd and even indices.

### Filters

Twig offers a wide [range of filters](https://twig.symfony.com/doc/3.x/filters/index.html) that you can apply using the pipe symbol.&#x20;

Here are some examples:

```twig
{{ my_var|abs }} {# Returns the absolute value of a number. #}
{{ my_var|capitalize }} {# Capitalizes the first character of a string. #}
{{ my_var|raw }}  {# Outputs a string without escaping HTML entities. #}
{{ my_var|upper }}  {#Converts a string to uppercase. #}
{{ my_var|lower }}  {# Converts a string to lowercase. #}
{{ my_var|round([precision, method]) }}  {# Rounds a number to the nearest integer. #}
{{ my_var|range(low,high[,step]) }} {# Generates a range of numbers or letters. #}
{{ my_var|date("d/m/Y") }} {# Formats a date or time according to a specified pattern. #}
{{ my_var|date_modify("+1 day") }} {# Modifies a date or time by adding or subtracting a specified interval. #}
{{ my_var|default("Default Value") }} {# Provides a default value if the variable is undefined or empty. #}
{{ my_var|replace({"search":"replace"}) }} {# Replaces occurrences of a specified substring with another. #}
{{ my_var|random(from[,max]) }} {# Generates a random number or selects a random item from an array. #}
```

Click on a specific filter name on [this page](https://twig.symfony.com/doc/3.x/filters/index.html) in the Twig Docs to access more detailed information.

{% hint style="success" %}
Note: We have created a custom build of Twig (to securely integrate it with WordPress), so some filters from the [official list](https://twig.symfony.com/doc/3.x/filters/index.html) may be missing. You can safely use the filters listed above or experiment with any filter from the [official list](https://twig.symfony.com/doc/3.x/filters/index.html) and let us know if it doesn't function as expected.
{% endhint %}

### Functions

Functions, unlike filters, serve different purposes and have distinct syntax.&#x20;

The key distinction between filters and functions lies in how they handle variables. Filters modify the variable they are applied to, as in "var|round," while functions operate on arguments independently.

{% code overflow="wrap" %}
```twig
{{ date("now") or date("10/10/2010") }} {# Creates a Date object from string (usually, used for comparison) #}
```
{% endcode %}

### Dates

When working with date filters and functions, it's important to consider the variable type. Strings containing dates and Date objects are distinct entities, and you should keep the following in mind:

1. Date objects cannot be displayed directly; you need to convert them into strings for this purpose.
2. When using conditional statements like `{% if %}`, you cannot directly compare date strings; you should first convert them into Date objects for comparison.

The "date" filter returns a string, whereas the "date\_modify" filter and "date" function return Date objects. Refer to the information below for more details.

#### Date filter (for output)

Converts a Date object into a string based on the specified format. If you provide a string, the filter will automatically parse the date using [strtotime](https://www.php.net/strtotime) and then convert it into a string in the requested format.

<pre class="language-twig"><code class="lang-twig">{{ "now"|date }} {# displays the current time #}
{{ my_date|date("Y") }} {# displays the year from the variable #}
<strong>{{ "10-10-2010"|date("d") }} {# displays the day from the string #}
</strong>{{ "+1 day"|date }} {# displays tomorrow's date #}
</code></pre>

#### Date\_modify filter (for modification)

Modifies a Date object according to the argument provided and returns the modified Date object. If you pass a string, the filter will automatically parse the date using [strtotime](https://www.php.net/strtotime).

<pre class="language-twig"><code class="lang-twig">{{ my_date|date_modify("+1 week") }} {# adds one week to the date #}
<strong>{{ "10-10-2010"|date_modify("+1 day") }} {# adds one day to the date #}
</strong></code></pre>

Keep in mind that this function **returns a Date object**, not a string. If you want to display the modified date, you should use the "date" filter to print the Date object in a specific format.

{% code overflow="wrap" %}
```twig
{{ my_date|date_modify("+1 week")|date("d/m/Y") }} {# modifies and prints the date #}
```
{% endcode %}

#### &#x20;Date function (for comparison)

Converts a string into a Date object, which is useful for comparison purposes.

<pre class="language-twig"><code class="lang-twig"><strong>{{ date("10-10-2010") }} {# creates a Date object from a string #}
</strong>{% if date(first_date) > date(second_date) %}
{{ first_date|date("d/m/Y") }}
{% endif %}
</code></pre>

Keep in mind that this function also **returns a Date object**, not a string. If you want to display the Date object, you should use the "date" filter to print it in a specific format.

```twig
{{ date("now")|date("d/m/Y") }}
```

**Available date formats**

* you can use any formats with the |date filter
* you can use most of the available date formats for the date() function. For example, "m-d-Y" (10-20-2011), "M d, Y" (October 20, 2011), or "d.m.Y" (20.10.2011).

{% hint style="info" %}
Tip: When you use the date parsing functions and filters, we recommend using the '`.timestamp`' property of the date field. This will save you from dealing with date parsing issues.\
\
For example, both US (e.g., mm/dd/yyyy) and European (e.g., dd/mm/yyyy) formats use the same delimiter, so the European format will be ignored in favor of the US format. This behavior is in line with the default behavior of the [strtotime](https://www.php.net/strtotime) function.



In this way using  '`datepicker.timestamp|date("d-m-Y")`' is the safe way which avoids it.
{% endhint %}

### Comments

```twig
{# All text within these brackets is available only for editors 
and will be removed from the final output. #}
```

## Our functions

We extended Twig to include additional WordPress-related functions, in addition to its built-in functions. You can find these extended functions listed below.

<pre class="language-twig"><code class="lang-twig">{{ print_r(my_array) }}
{# calls the built-in PHP print_r function (displays the array for debug purposes) #}

{{ wp_interactivity_state('name', {stateArg:'some'}) }}
{# calls the built-in WordPress wp_interactivity_state function #}

<strong>{{ wp_interactivity_data_wp_context({contextArg:'some'}) }}
</strong>{# calls the built-in WordPress wp_interactivity_data_wp_context function #}

{{ paginate_links({total:'10',}) }}
{# calls the built-in WordPress paginate_links function #}
</code></pre>

You'll use the interactivity functions in _Views_ when employing the [WP Interactivity API](../css-and-js/wordpress-interactivity-api), while `paginate_links` is used inside _Cards_ when the 'Source: Page content' option is chosen.

### Pro only <a href="#our-functions" id="our-functions"></a>

{% hint style="warning" %}
[Note: These functions are only available in Advanced Views Pro.](../../getting-started/installation/advanced-views-pro)
{% endhint %}

```twig
{{ _query_argument('my-category-id') }} 
{# retrieves the argument from the current page URL ($_GET in PHP) #}

{{ _is_user_with_role("role") }} 
{# checks if user has the specified role. 
You can pass user id as the second argument, or it'll use the current user id #}

{{ _is_user_logged_in() }} 
{# calls is_user_logged_in() from WP #}

{{ _site_url("/my-page") }} 
{# calls site_url() from WP #}

{{ _home_url() }} 
{# calls home_url() from WP #}

{{ __("Some label") }} 
{# translates the label. 
You can pass the text domain as the second argument, 
or it'll use the "Text Domain" of your theme 
(declared in the headings of the style.css file of your theme) #}
```

## Our filters (Pro)

```twig
{{ "Some label"|translate }} 
{# translates the label (alternative to the '__' function described above)
You can pass the text domain as the second argument, 
or it'll use the "Text Domain" of your theme 
(declared in the headings of the style.css file of your theme) #}
```

## Custom functions (Pro)

In the Pro version of the plugin, you can add your own functions. Check [this hooks guide](../../../customization/filters-and-hooks#custom-twig-functions-pro) to learn details.

## Custom filters (Pro)

In the Pro version of the plugin, you can add your own filters. Check [this hooks guide](../../../customization/filters-and-hooks#custom-twig-filters-pro) to learn details.

## Twig version

If you're wondering, Advanced Views uses version 3.7.1 of the Twig engine.
