# OpenCart Twig Templates: Variables, Filters and Includes in 3.0 and 4.1

> How Twig templates work in OpenCart 3.0 and 4.1: where the files live, how the controller passes variables, which filters you need, how to assemble a page from parts and how to clear the cache.

Джерело: https://opencartcode.com/en/wiki/dev-mvc/opencart-twig-templates
OpenCart: 3.0, 4.1
Оновлено: 2026-11-24

Twig in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) is a template engine that receives an array of `$data` from the [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) and turns the `.twig` file into HTML. The controller calls `$this->load->view('маршрут', $data)`, the core finds the required file, and renders it through the Twig library. The logic is the same in OpenCart 3.0 and 4.1, but file paths, sub-template inclusion, and debugging differ. Below is how it works and where developers most often make mistakes.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## Where do Twig templates live and how does the controller load them?

The template is the last link in the MVC-L chain. How the controller, model, template, and [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) relate to each other is explained in detail in the article about [the MVC-L architecture in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/opencart-mvc). Here we focus on where to put the file and how to call it.

| What | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Storefront templates | `catalog/view/theme/default/template/` | `catalog/view/template/` |
| Admin templates | `admin/view/template/` | `admin/view/template/` |
| Module template | `.../template/extension/module/my_banner.twig` | `extension/mycode/catalog/view/template/module/my_banner.twig` |
| Call in the controller | `load->view('extension/module/my_banner', $data)` | `load->view('extension/mycode/module/my_banner', $data)` |

The `.twig` extension is not written in the route: the core adds it automatically. You can find the full directory map in the overview of [OpenCart file structure](https://opencartcode.com/en/wiki/dev-architecture/opencart-file-structure).

A typical [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) module controller returns the generated HTML as a string, and the page controller passes it on in the response:

```php
// Модуль (вставляється в схему) — повертає рядок
return $this->load->view('extension/module/my_banner', $data);

// Повноцінна сторінка — віддає HTML у Response
$this->response->setOutput($this->load->view('extension/module/my_banner', $data));
```

**OpenCart 3.0:** on the storefront, the route is prefixed with the active theme's directory. If the file is not in your theme, the file from `default` is used. Because of this, a module may "not see" its template if it was placed only in a custom theme while the store runs on a different one.

**OpenCart 4.1:** the `extension/mycode/...` route is converted into a path inside the `extension/mycode/` directory. You can see exactly how this happens in the Twig class code in the next section. For more on how `load->view` is related to events, see the material about [the Loader in OpenCart](https://opencartcode.com/en/wiki/dev-architecture/opencart-loader).

## How does OpenCart render a template: what's inside the Twig class

The wrapper around the library is located in `system/library/template/twig.php`. It is worth reading at least once, because almost all the specifics of working with templates follow from it.

`system/library/template/twig.php` · OpenCart 3.0.5.1 · lines 22–35

```php
		// initialize Twig environment
		$config = array(
			'autoescape'  => false,
			'debug'       => false,
			'auto_reload' => true,
			'cache'       => DIR_CACHE . 'template/'
		);

		try {
			$loader = new \Twig\Loader\ArrayLoader(array($filename . '.twig' => $code));

			$twig = new \Twig\Environment($loader, $config);

			return $twig->render($filename . '.twig', $this->data);
```

In 3.0, the template is first read into a `$code` string and passed to `ArrayLoader`, which contains exactly one template. This scheme allows you to substitute modified code for the file, but Twig "sees" nothing else. We will return to the consequences of this in the section on include.

`system/library/template/twig.php` · OpenCart 4.1.0.4 · lines 103–119

```php
		try {
			// Initialize Twig environment
			$config = [
				'charset'     => 'utf-8',
				'autoescape'  => false,
				'debug'       => true,
				'auto_reload' => true,
				'cache'       => DIR_CACHE . 'template/'
			];

			$twig = new \Twig\Environment($loader, $config);

			if ($config['debug']) {
				$twig->addExtension(new \Twig\Extension\DebugExtension());
			}

			return $twig->render($file, $data);
```

In 4.1, `FilesystemLoader` with the root at `DIR_OPENCART` is used by default. `ArrayLoader` is connected only when modified code is passed. Template [extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) are registered as "namespaces" via `addPath()`, and the `render()` method matches the beginning of the route with these paths:

`system/library/template/twig.php` · OpenCart 4.1.0.4 · lines 79–91

```php
		$parts = explode('/', $filename);

		foreach ($parts as $part) {
			if (!$namespace) {
				$namespace .= $part;
			} else {
				$namespace .= '/' . $part;
			}

			if (isset($this->path[$namespace])) {
				$file = $this->path[$namespace] . substr($filename, strlen($namespace) + 1) . '.twig';
			}
		}
```

Here is how the path from the controller to HTML looks:

```mermaid
flowchart TD
    A["Controller: $data + load->view()"] --> B["view/*/before event"]
    B --> C["Language variables and theme are added to data"]
    C --> D["Template\Twig class: path to .twig"]
    D --> E{"Is there modified code?"}
    E -- "yes" --> F["ArrayLoader from string"]
    E -- "no" --> G["File from disk"]
    F --> H["Compilation into template/ cache"]
    G --> H
    H --> I["HTML in Response"]
```

## Where do variables in the template come from and how do you output them?

Each key of the `$data` array becomes a template variable. The `$data['products']` key turns into `{{ products }}`. Elements of nested arrays are read via a dot: `product.name` means `$product['name']`. Twig uses the same notation for object properties and methods, but passing core objects such as `$this->cart` or `$this->customer` into the template is a bad idea. Prepare everything the template needs in the controller as simple arrays and strings.

```twig
<div class="my-banner">
  <h3>{{ heading_title }}</h3>
  {% if products %}
    <ul>
      {% for product in products %}
        <li>
          <a href="{{ product.href }}">{{ product.name }}</a> — {{ product.price }}
          {% if product.special %}<s>{{ product.special }}</s>{% endif %}
        </li>
      {% endfor %}
    </ul>
  {% else %}
    <p>{{ text_empty }}</p>
  {% endif %}
</div>
```

Language strings such as `heading_title` or `text_empty` are often not assigned manually in the controller. In the standard build, an event fires before rendering and adds everything loaded via `$this->load->language()` to the data. Keys you explicitly set in `$data` are not overwritten. So `{{ text_empty }}` works if the module's language file has been loaded.

Keep the following in mind:

- A nonexistent variable does not cause an error: Twig simply outputs an empty string. Because of this, errors in key names are easy to miss.
- Format prices in the controller via `$this->currency->format()`, because the template doesn't know the session currency. The template should receive a ready string such as "1 250,00 грн".
- Build links in the controller via `$this->url->link()`. In the admin, `user_token` is always added to links, so it's better not to build URLs manually in the template.
- Comparisons in conditions work as in PHP: `{% if status == 1 %}`, `{% if product.quantity > 0 %}`. To check whether a key exists, use `{% if foo is defined %}`.

For how the controller collects data and what it returns, read separately: [OpenCart controller: data, template, and child controllers](https://opencartcode.com/en/wiki/dev-mvc/opencart-controller).

## Which Twig filters are really needed in OpenCart?

A filter is written after a vertical bar and transforms the value: `{{ name|upper }}`. Filters can be chained: `{{ description|striptags|slice(0, 150) }}`. Below are the ones that most often appear in themes and modules.

| Filter | Example | Purpose |
| --- | --- | --- |
| `e` / `escape` | `{{ comment\|e }}` | Escapes HTML in data received from the user |
| `escape('js')` | `'{{ text_confirm\|escape('js') }}'` | Safely inserts a string into JavaScript |
| `json_encode` | `var items = {{ items\|json_encode }};` | Passes an array to JS, for example for analytics |
| `default` | `{{ product.sku\|default('—') }}` | Substitutes a fallback value for an empty variable |
| `length` | `{% if products\|length > 4 %}` | Counts the number of items, for example for a slider |
| `striptags`, `slice` | `{{ text\|striptags\|slice(0, 120) }}` | Creates a short excerpt from an HTML description |
| `nl2br` | `{{ comment\|e\|nl2br }}` | Converts line breaks into order comments |
| `join`, `replace` | `{{ tags\|join(', ') }}` | Joins an array into a string or replaces a substring |

> In both versions, `autoescape` is disabled, so `{{ var }}` outputs the value "as is", and the `|raw` filter changes nothing. Protection against XSS is your responsibility. OpenCart passes incoming GET/POST data through `htmlspecialchars` in the Request class, so form data usually already reaches the database escaped. That is exactly why product descriptions in controllers are decoded via `html_entity_decode()`. If you take data while bypassing Request (raw `php://input`, an external API, an import), escape it in the template via `|e`.

How Request sanitizes input is described in detail in the material [Request and Response in OpenCart](https://opencartcode.com/en/wiki/dev-architecture/opencart-request-response). You cannot add a custom filter through settings: `\Twig\Environment` is created inside `render()` every time anew. To do this, you would have to modify the wrapper class. It is simpler to prepare the values in the controller.

## How to include template parts: child controllers, include, and extends

OpenCart assembles the header, footer, and columns not through Twig inheritance but through child controllers. The page controller runs other controllers and places the received HTML strings into `$data`:

```php
$data['column_left'] = $this->load->controller('common/column_left');
$data['content_top'] = $this->load->controller('common/content_top');
$data['footer']      = $this->load->controller('common/footer');
$data['header']      = $this->load->controller('common/header');
```

In the page template, these variables are simply output: `{{ header }}` … `{{ footer }}`. The advantage of this approach is that each fragment has its own logic and language file, and can be intercepted by events.

### OpenCart 3.0: why {% include %} doesn't work

As seen in the code above, in 3.0 `ArrayLoader` contains only the current template. Therefore `{% include 'common/foo.twig' %}` and `{% extends %}` fail with the "template not found" error. If you need a fragment for reuse, move it into a separate controller method and render it through `load->view`. Another option: prepare a string in `$data` and output it.

### OpenCart 4.1: include is possible, but with a full path

`FilesystemLoader` in 4.1 has the root `DIR_OPENCART`, so the inclusion formally works if you specify the path from the installation root:

```twig
{% include 'extension/mycode/catalog/view/template/module/_item.twig' %}
```

The downsides are obvious. The path is hard-coded to the file location, the sub-template bypasses `view/*/before` events, and in the admin everything breaks if the `admin` directory is renamed for security reasons. The 4.1 core barely uses this. For modules, it is more reliable to stay with child controllers or separate `load->view` calls.

## Why don't template changes show up, and how do you debug Twig?

Compiled templates are stored in `DIR_CACHE . 'template/'`. In 3.0 this is usually `system/storage/cache/template/`, in 4.1 by default also `system/storage/cache/template/`, and after moving storage outside the root (as the admin recommends) — `<новий шлях до storage>/cache/template/`. The `auto_reload` parameter is enabled, so a changed Twig file is recompiled automatically. If changes still don't appear, the cause is usually one of the following:

1. **You are editing the wrong file.** In 3.0, check which theme is selected in "System → Settings" when editing the store, and whether the file from `default` is being substituted. The themes themselves and their directories are found in "Extensions → Extensions", type "Themes".
2. **The template is overridden in the theme editor.** Code saved in "Design → Theme Editor" is stored in the database and takes priority over the file on disk.
3. **An OCMOD modification is active.** After changes, you need to refresh modifications in "Extensions → Modifications" using the "Refresh" button.
4. **The browser or CDN is caching.** This particularly applies to CSS/JS files loaded from the template.

Theme editor: selecting the store and template whose code will be saved in the database over the file · OpenCart 4.1.0.4

The `cache/template/` directory can be safely cleared; it will be regenerated. Clearing is also available from the dashboard via the developer settings button. For what else is stored in storage and what can be deleted from it, see the article [the storage directory in OpenCart](https://opencartcode.com/en/wiki/dev-architecture/opencart-storage).

**OpenCart 4.1:** `debug` is enabled and `DebugExtension` is connected, so the `dump()` function is available in the template:

```twig
<pre>{{ dump(products) }}</pre>
{# або всі змінні шаблону #}
<pre>{{ dump() }}</pre>
```

**OpenCart 3.0:** `debug` is disabled, so `dump()` does not exist. Check data in the controller via `$this->log->write(print_r($data, true))` and look at the result in "System → Maintenance → Error Logs". A syntax error in a 3.0 template stops execution with the message "Could not load template". In 4.1 it throws an exception with the same text, and on the storefront this looks like a blank page or a 500 error, depending on error display settings.

> Do not leave `dump()` in a production 4.1 template: it will output the data structure to every visitor. Before release, search the project for the `dump(` string.

It is not advisable to edit core and third-party theme templates directly, because updates will overwrite the changes. For targeted edits, use OCMOD (details in the article [OCMOD in OpenCart: code edits without changing system files](https://opencartcode.com/en/blog/ocmod-v-opencart-pravki-kodu-bez-zmini-sistemnix-failiv)) or the `view/маршрут/before` event, which appends variables to the data.

Modifications: the "Refresh" button rebuilds changed templates after installing OCMOD · OpenCart 4.1.0.4

## Summary

- Twig in OpenCart receives the `$data` array from the controller. Array keys become variables, and nested elements are read via a dot.
- Paths differ. **OpenCart 3.0:** `catalog/view/theme/<тема>/template/` with a fallback to `default`. **OpenCart 4.1:** `catalog/view/template/`, and modules are located in `extension/<код>/.../view/template/` via the `addPath()` namespaces.
- `autoescape` is disabled: escape data from untrusted sources via `|e`, and insert it into JS via `escape('js')` or `json_encode`.
- Assemble the page from child controllers. In 3.0, `include`/`extends` do not work; in 4.1 they work only with a full path from the root.
- If changes are not visible, check the theme, the theme editor, OCMOD, and the `cache/template/` directory. In 4.1, `dump()` is available for debugging.

Next, it is worth understanding how the core finds the controller itself by the `route=` parameter. See the article [the route= routing in 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-mvc/opencart-route). All materials about controllers, models, templates, and language files are collected in the section [MVC-L: controllers, models, templates](https://opencartcode.com/en/wiki/dev-mvc).

## FAQ

**Can you use old .tpl templates in OpenCart instead of Twig?**

No. .tpl files belong to OpenCart 2.x. In 3.0 and 4.1 the standard engine is Twig, so old templates need to be rewritten in Twig syntax: replace PHP inserts with {{ }} and {% %}.

**Can you call PHP functions directly from an OpenCart Twig template?**

Only those available as built-in Twig filters and functions. Arbitrary PHP does not run in a template, so do calculations, price formatting and link building in the controller.

**How do you pass data into a third-party module's template without changing its controller?**

Register an event with the trigger view/template_route/before. The handler receives the data array by reference and can add or change variables before rendering.

**Does the number of Twig templates affect store speed?**

Only the first render after changes is noticeably slower, when the template is compiled into a PHP class. After that the cache is used, so database queries in controllers and models have a much bigger impact on speed.

**Why can't the module template be found in the 4.1 admin even though the file exists?**

Most often the route in load->view does not match the structure of extension/код/admin/view/template/. Check that the route starts with extension/код/ and that the rest of the path matches the subfolders after template/.
