Twig in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → is a template engine that receives an array of $data from the controllerCode that receives a request and prepares data. More in the glossary → and turns the .twig file into HTML. The controller calls $this, 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 fileA PHP file with interface texts, separate for each language. More in the glossary → relate to each other is explained in detail in the article about the MVC-L architecture in OpenCart. Here we focus on where to put the file and how to call it.
| What | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
| Storefront templates | catalog/ | catalog/ |
| Admin templates | admin/ | admin/ |
| Module template | .../ | extension/ |
| Call in the controller | load | load |
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.
A typical storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → module controller returns the generated HTML as a string, and the page controller passes it on in the response:
// Модуль (вставляється в схему) — повертає рядок
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/ 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.
How does OpenCart render a template: what's inside the Twig class
The wrapper around the library is located in system/. It is worth reading at least once, because almost all the specifics of working with templates follow from it.
system/ · OpenCart 3.0.5.1 · lines 22–35
// 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/ · OpenCart 4.1.0.4 · lines 103–119
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 extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → are registered as "namespaces" via addPath(), and the render() method matches the beginning of the route with these paths:
system/ · OpenCart 4.1.0.4 · lines 79–91
$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:
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.
<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 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, because the template doesn't know the session currency. The template should receive a ready string such as "1 250,00 грн".->currency ->format() - Build links in the controller via
$this. In the admin,->url ->link() user_tokenis 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.
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 |
How Request sanitizes input is described in detail in the material Request and Response in OpenCart. 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:
$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/ 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:
{% 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/, in 4.1 by default also system/, and after moving storage outside the root (as the admin recommends) — <новий шлях до storage>/. 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:
- 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
defaultis being substituted. The themes themselves and their directories are found in "Extensions → Extensions", type "Themes". - 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.
- An OCMOD modification is active. After changes, you need to refresh modifications in "Extensions → Modifications" using the "Refresh" button.
- The browser or CDN is caching. This particularly applies to CSS/JS files loaded from the template.

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.
OpenCart 4.1: debug is enabled and DebugExtension is connected, so the dump() function is available in the template:
<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 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.
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) or the view/ event, which appends variables to the data.

Summary
- Twig in OpenCart receives the
$dataarray from the controller. Array keys become variables, and nested elements are read via a dot. - Paths differ. OpenCart 3.0:
catalog/with a fallback toview/ theme/ <тема>/ template/ default. OpenCart 4.1:catalog/, and modules are located inview/ template/ extension/via the<код>/ .../ view/ template/ addPath()namespaces. autoescapeis disabled: escape data from untrusted sources via|e, and insert it into JS viaescape('js')orjson_encode.- Assemble the page from child controllers. In 3.0,
include/extendsdo 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. All materials about controllers, models, templates, and language files are collected in the section MVC-L: controllers, models, templates.