---
title: Twig Features | Shopware Community Hub
description: >-
  Learn common Twig tags, filters, and functions in Shopware and use them to
  make storefront templates more dynamic.
canonical_url: 'https://hub.shopware.com/learn/unit/twig-features'
---

# Twig Features

<LearningObjectives>

- Use common Twig tags and keywords such as `set`, `if`, `for`, `with`, and `ignore missing`.
- Apply filters such as `default`, `currency`, and `sw_sanitize` to prepare template output.
- Read plugin configuration values in Twig with `config()` and use them for conditional rendering.
- Identify custom Twig functions as an advanced extension point.

</LearningObjectives>

# Twig Features

You already used `sw_extends`, `sw_include`, blocks, and `parent()`. These features let you extend existing storefront templates safely.

Now you will look at the Twig features that make templates more dynamic: tags and keywords for control flow, filters for output formatting, and functions for reading values such as plugin configuration.

## Tags and Keywords

Twig tags and keywords control what happens inside a template. You use them to set variables, include reusable template parts, check conditions, and loop through collections.

### Define Values With `set`

The `set` tag defines a variable directly inside a template. This is useful when you want to store a value or provide a fallback value for later output.

```twig
{% set variable_name = 'Value' %}
```

### Pass Values Into Includes With `with`

You can pass values into another template with the `with` keyword when you include it with `sw_include`. This makes reusable template parts flexible.

It is also common to define fallback values in the included template. That way, the included template still works if no value is passed.

The following reusable template is given as `custom-block.html.twig`:

```twig
{% block custom_block %}
  {% set custom_variable = 'Hello World' %}
  <h1>
    {{ custom_variable }}
  </h1>
{% endblock %}
```

You can include this template and override the variable:

```twig
{% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' with {
    custom_variable: "Greetings."
} %}
```

This renders:

```html
<h1>Greetings.</h1>
```

You can also pass an existing variable instead of a hard-coded value:

```twig
{% set welcoming = "Greetings." %}
{% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' with {
    custom_variable: welcoming
} %}
```

If you skip `with`, the included template uses its own fallback:

```twig
{% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' %}
```

This renders:

```html
<h1>Hello World</h1>
```

### Ignore Optional Templates With `ignore missing`

The `ignore missing` keyword can be used with `sw_include`. It prevents an error if the included template does not exist.

Use this only when a template is truly optional. If the template is required for the feature, a missing file should fail clearly during development.

```twig
{% set welcoming = "Greetings." %}
{% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' ignore missing with {
    custom_variable: welcoming
} %}
```

You can also use it without `with`:

```twig
{% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' ignore missing %}
```

### Render Conditionally With `if`

The `if` tag renders content only when a condition is true. In storefront templates, this is useful for optional markup, plugin configuration, or product-specific output.

```twig
{% set welcoming = "Hi there." %}

{% if welcoming is same as("Greetings.") %}
    {% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' with {
        custom_variable: welcoming
    } %}
{% else %}
    {% sw_include '@Storefront/storefront/frontend-essentials/custom-block.html.twig' %}
{% endif %}
```

<Callout title="Strict Comparison" type="info">

Twig uses `same as` for strict comparison. It checks the value and the type.

</Callout>

For more detail, see the official [Twig documentation for `if`](https://twig.symfony.com/doc/3.x/tags/if.html).

### Loop Through Items With `for`

The `for` tag loops through a collection of items. In storefront templates, this is useful when you render product media, properties, deliveries, or other repeated data.

```twig
{% set products = ['Shirt', 'Shoes', 'Hat'] %}

<ul>
  {% for product in products %}
    <li>{{ product }}</li>
  {% endfor %}
</ul>
```

This renders:

```html
<ul>
  <li>Shirt</li>
  <li>Shoes</li>
  <li>Hat</li>
</ul>
```

<Callout title="Loop Variables" type="info">

Inside a `for` loop, Twig provides loop variables such as `loop.index` for the current iteration and `loop.length` for the total number of items.

</Callout>

For more detail, see the official [Twig documentation for `for`](https://twig.symfony.com/doc/3.x/tags/for.html).

## Filters

Filters modify a value before it is rendered. You call a filter with the `|` syntax.

In storefront templates, filters are common when you want to provide fallback text, format prices, or render safe HTML.

### Provide Fallbacks With `default`

The `default` filter provides a fallback if a variable is not defined or empty. This is useful for reusable templates, because the template can still render a useful value when no value is passed from the parent template.

```twig
{% block custom_block %}
  <h1>
    {{ custom_variable|default('Hello World') }}
  </h1>
{% endblock %}
```

If `custom_variable` is missing or empty, Twig renders `Hello World`. If it exists, Twig renders the actual value.

### Format Prices With `currency`

The `currency` filter formats a number as a currency value by using the active sales channel context.

```twig
{{ product.calculatedPrice.unitPrice|currency }}
```

The output depends on the active currency and locale of the sales channel.

For example, the same value may be rendered as `12,99 €` in a German sales channel or as `€12.99` in an English sales channel.

If you need to explicitly set a currency and locale, you can use Twig's native `format_currency` filter:

```twig
{{ 12.99|format_currency('EUR', {}, 'de-DE') }}
{{ 12.99|format_currency('EUR', {}, 'en-GB') }}
```

### Render Safe HTML With `sw_sanitize`

The `sw_sanitize` filter is a Shopware-specific filter for rendering HTML content safely. It removes potentially dangerous tags and attributes, such as `<script>` tags or event handler attributes, while keeping allowed HTML.

This helps prevent cross-site scripting (XSS) when HTML content is rendered in the storefront.

```twig
{% set input_html = '<p>Hello <b>World</b> <script>alert("XSS")</script></p>' %}
{{ input_html|sw_sanitize }}
```

The output keeps safe HTML and removes the `<script>` tag.

## Functions

Functions execute a specific task and return a value. They are called with the `()` syntax.

Twig provides native functions, and Shopware adds storefront-specific functions. One important Shopware example is `config()`.

<Callout title="Tags vs. Functions" type="info">

Twig provides native `include` and `extends` tags. Shopware provides `sw_include` and `sw_extends` so templates are loaded according to Shopware's storefront inheritance rules.

</Callout>

### Read Plugin Configuration With `config()`

Shopware provides the Twig function `config()`. You can use it to read system configuration values inside a Twig template.

The mental model is simple: A plugin defines a configuration field, a merchant changes the value in the Administration, and Twig can read that value with `config()`.

```twig
{{ config('AcademyFrontendEssentials.config.showColorfulTab') }}
```

In this example, `AcademyFrontendEssentials.config.showColorfulTab` is the full configuration key. It contains the plugin name, the `config` namespace, and the field name.

In the example plugin, this value controls whether an additional colorful tab is shown on the product detail page.

Check out the git tag and open the template:

```shell
git checkout tags/LU-03-functions
```

The value read by `config()` comes from a field in `[plugin_root]/src/Resources/config/config.xml`. This file defines configuration fields that can be changed in the Shopware Administration.

In this example, the plugin defines a boolean field named `showColorfulTab`:

```xml
<?xml version="1.0" encoding="UTF-8"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/shopware/trunk/src/Core/System/SystemConfig/Schema/config.xsd">

  <card>
    <title>Basic settings</title>

    <input-field type="bool">
      <name>showColorfulTab</name>
      <label>Display colorful tab</label>
    </input-field>
  </card>

</config>
```

The goal is to make the custom tab configurable. If the field is enabled in the Shopware Administration, the tab should be visible. If it is disabled, the tab should not be rendered.

This is how the condition is used in `cms-element-product-description-reviews.html.twig`:

```twig
{% sw_extends '@Storefront/storefront/element/cms-element-product-description-reviews.html.twig' %}

{% block element_product_description_reviews_tabs_navigation_review %}
    {{ parent() }}

    {% block frontend_essentials_custom_tabs_navigation %}
        {% if config('AcademyFrontendEssentials.config.showColorfulTab') is same as(true) %}
            <li class="nav-item">
                <a class="nav-link"
                   id="custom-review-tab"
                   data-bs-toggle="tab"
                   href="#custom-review-content"
                   role="tab"
                   aria-controls="custom-review-content"
                   aria-selected="false"
                >
                    Colorful div tab
                </a>
            </li>
        {% endif %}
    {% endblock %}
{% endblock %}

{% block element_product_description_reviews_tabs_content %}
    {{ parent() }}

    {% block frontend_essentials_custom_tabs_content %}
        {% if config('AcademyFrontendEssentials.config.showColorfulTab') is same as(true) %}
            <div class="tab-pane fade"
                 id="custom-review-content"
                 role="tabpanel"
                 aria-labelledby="custom-review-tab"
            >
                {% sw_include '@Storefront/storefront/frontend-essentials/color.html.twig' %}
            </div>
        {% endif %}
    {% endblock %}
{% endblock %}
```

The same condition is used in two places:

- Around the clickable tab in `element_product_description_reviews_tabs_navigation_review`.
- Around the matching tab content in `element_product_description_reviews_tabs_content`.

This keeps both parts of the feature in sync. The clickable tab and the tab content are either both rendered or both hidden. That prevents incomplete storefront behavior, such as a tab without matching content.

<Callout title="Expected Result" type="success">

When `showColorfulTab` is enabled in the plugin configuration, an extra tab appears on the product detail page.

</Callout>

<Callout title="IDE Support" type="info">

If you use PhpStorm, the Symfony plugin can improve autocompletion and navigation for Twig-related files.

</Callout>

<CollapsibleSection title="Custom Twig Functions (Advanced)">

You can also create custom Twig functions in Shopware. This is an advanced extension point where a service extends `Twig\Extension\AbstractExtension` and provides new functions for Twig templates.

This learning unit does not implement a custom function. The important point here is that Twig can be extended when built-in and Shopware-provided functions are not enough.

See the official guide: [Add custom Twig function](https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-twig-function.html).

<Callout title="Custom Filters and Functions" type="info">

Custom filters and functions are useful for advanced projects, but they are not part of this essentials course from an implementation perspective.

</Callout>

</CollapsibleSection>

<ArticleQuestionnaire>
  <ArticleQuestionnaireQuestion>Which Twig feature reads a Shopware plugin configuration value inside a template?</ArticleQuestionnaireQuestion>
  <ArticleQuestionnaireAnswer>sw_sanitize</ArticleQuestionnaireAnswer>
  <ArticleQuestionnaireAnswer correct>config()</ArticleQuestionnaireAnswer>
  <ArticleQuestionnaireAnswer>ignore missing</ArticleQuestionnaireAnswer>
</ArticleQuestionnaire>

## Summary

In this learning unit, you learned how to:

- Use Twig tags and keywords such as `set`, `if`, `for`, `with`, and `ignore missing`.
- Pass values into included templates and provide fallback values for reusable template parts.
- Apply filters such as `default`, `currency`, and `sw_sanitize`.
- Read plugin configuration values with `config()` and use them for conditional rendering.
- Recognize custom Twig functions as an advanced way to extend Twig behavior.

With this knowledge, you can make your storefront templates more dynamic, flexible, and maintainable.
