Event view 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 an event that the loader triggers before rendering a template (view/…/before) and after it (view/…/after). In a before handler you can add variables to the template, substitute a different file, or change the Twig code itself. In an after handler you can edit the finished HTML. All of this works without editing theme files, but the result depends on the version and on the event priority.
Examples are for OpenCart 4.1. In 4.0.x, model triggers and event handling differ. The general event mechanics (trigger matching, return values) are covered in the article OpenCart event system, and registration through addEvent and execution order are covered in the article module event registration and sort_order.
What does the view/*/before handler receive, and what does the trigger react to?
The event fires every time the controllerCode that receives a request and prepares data. More in the glossary → calls $this. The template route is the path without the extension .twig: the product card on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → is rendered as product/product, and the product form in the admin as catalog/. Therefore, module triggers look like this:
catalog/: only the product card on the storefront;view/ product/ product/ before admin/: the product form in the admin;view/ catalog/ product_form/ before catalog/: any storefront template (use with caution, see the last section).view/ */ before
Handler arguments are passed by reference:
| Argument | OpenCart 3.0 | OpenCart 4.1 | What you can do with it |
|---|---|---|---|
&$route | yes | yes | substitute a different template |
&$data | yes | yes | add or change template variables |
&$code | yes | yes | pass Twig source code instead of a file |
&$output | no | yes | set finished HTML and skip rendering |
The $code variable is usually empty on input. If the handler fills it with a string of Twig code, the renderer will use that string instead of the file. This is exactly why the event allows changing template markup without creating file copies.
OpenCart 3.0: if the before handler returns a string, rendering is skipped and the string becomes the result. OpenCart 4.1: the returned value is ignored; for the same effect, fill $output instead.
How do I add my own variables to the template?
The simplest and safest technique: append keys to $data. The theme template does not change, and the new variables become available in it as {{ my_badge }}. This way the module can provide data to a theme that already knows about these variables, or to its own template connected in the following steps.
Example
// OpenCart 4.1: extension/my_module/catalog/controller/module/my_module.php
public function productView(string &$route, array &$data, string &$code, string &$output): void {
if (!$this->config->get('module_my_module_status')) {
return;
}
$data['my_badge'] = $this->config->get('module_my_module_badge');
}
// OpenCart 3.0: catalog/controller/extension/module/my_module.php
public function productView(&$route, &$data, &$code) {
if (!$this->config->get('module_my_module_status')) {
return;
}
$data['my_badge'] = $this->config->get('module_my_module_badge');
}
Note two details. First, in 3.0 the handler returns nothing: a return value of return would cancel rendering. Second, $data already contains everything the controller prepared, so the handler can not only add values but also change them, for example rewriting $data['heading_title'] or filtering the $data['products'] array.
Template texts are conveniently taken from the module's language fileA PHP file with interface texts, separate for each language. More in the glossary →. The core service handler event/language works on view/*/before with priority 998 and adds to $data all loaded language strings that are not there yet. So if your handler with a lower priority calls $this, the module strings will get into the template automatically, and the core will not overwrite keys you set manually in $data. For the structure of language files, see the article OpenCart language files.
How do I replace the template with my own file?
If the markup needs to be changed substantially, it is simpler to supply your own template: the handler assigns $route a new route, and the loader renders that one with the same $data. The file path differs between versions.
OpenCart 3.0
Storefront templates are located in catalog/. The theme directory is chosen by the core service handler event/theme with priority 500: it checks whether the file {маршрут}.twig exists in the active theme directory, and if not, it uses default/template/. Therefore:
- Place the module file, for example, in
catalog/.view/ theme/ default/ template/ extension/ module/ my_product.twig - In the handler, assign
$route = 'extension/.module/ my_product'; - Register the event with
sort_orderlower than 500, so thatevent/themelooks up the directory for the new route.
If the handler runs after event/theme, the directory will be selected for the old route, and with a theme that has its own copy of the product card, your file will be searched for in the wrong place.
OpenCart 4.1
Core templates are located in catalog/, and extension templates in extension/. The extension path registers startup/extension for each installed extension, so the route extension/ will point to the file extension/. There is no theme directory selection here, so the priority for route substitution is not critical.
How do I change Twig code without copying the whole template?
The most flexible technique: read the template's source code, replace a fragment in it, and pass the result to $code. The theme remains the source of the markup, and the module adds only its own piece. It is important that the handler runs after event/theme (priority 500): in 3.0 that one selects the theme directory, and in both branches it substitutes into $code the template version from "Design → Theme Editor" if it is saved in the database. A handler with a lower priority will lose its edit $code as soon as someone edits the template in the editor.
Example
// OpenCart 4.1, подія catalog/view/product/product/before з sort_order 600
public function productCode(string &$route, array &$data, string &$code, string &$output): void {
if (!$code) {
$file = DIR_TEMPLATE . $route . '.twig';
if (!is_file($file)) {
return;
}
$code = file_get_contents($file);
}
$search = '<div id="product">';
if (strpos($code, $search) !== false) {
$code = str_replace($search, '{% if my_badge %}<span class="badge">{{ my_badge }}</span>{% endif %}' . $search, $code);
}
}
For 3.0, only the file path changes: the theme directory is already recorded in the settings at this point, so the file is looked up as DIR_TEMPLATE . $this, where DIR_TEMPLATE of the 3.0 storefront points to catalog/view/theme/.
Pitfalls of this technique:
- The search string may not be found. Another theme has different markup, and
str_replacewill silently change nothing. Checkstrpos()and, if needed, write to the log so you can see on which themes the insertion did not work. - In 4.1 the route may already be modified. The core
event/with priority 0 substitutesmodification.view extension/ocmod/…if a copy of the template modified by OCMOD exists. Then the pathDIR_TEMPLATE . $routewill not exist, and the handler above will simply exit at theis_file()check. - A syntax error in the insertion breaks the whole page, because Twig compiles the entire template code. Test the insertion on a store test copy.
When is it better to edit the finished HTML in view/*/after?
The view/…/after event receives &$route, &$data, &$output, where $output is the already generated HTML. It can be changed with ordinary string operations: add a script before </head>, an attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary → to a tag, or a block after a certain element.
Example
// OpenCart 4.1, подія catalog/view/common/header/after
public function headerAfter(string &$route, array &$data, string &$output): void {
$output = str_replace('</head>', '<meta name="my-module" content="1">' . "\n" . '</head>', $output);
}
OpenCart 3.0: you can also change $output by reference, and in addition the core will substitute the result if the after handler returns a string. However, returning stops the other handlers of this event, so editing the argument is safer.
Comparison of techniques:
| Technique | When it fits | Risk |
|---|---|---|
Variables in $data | the theme already outputs the variable, or the template is yours | minimal |
Replacing $route | the page needs to be rebuilt entirely | theme changes stop applying |
Editing $code | targeted insertion into Twig markup with variables | dependence on the theme's markup |
Editing $output in after | insertion into finished HTML without Twig logic | dependence on HTML, working with large strings |
In 4.1 there is one more option: fill $output in the before handler. Then rendering does not run at all, which can be useful for caching a heavy block. After events will still fire in this case.
In what order do the core template handlers run?
In the before phase, together with your handler, the core handlers from the configs system/ and system/ run. A lower priority runs earlier:
flowchart TD
A["load->view: route and data"] --> B["0: event/modification.view (4.1 only)"]
B --> C["module, sort_order up to 500: data, route"]
C --> D["500: event/theme, theme directory and theme editor"]
D --> E["module, sort_order from 501: code edit"]
E --> F["998: event/language, language strings"]
F --> G["Twig rendering"]
G --> H["view/after: output edit"]
The diagram applies to the storefront. In the 3.0 admin, view/*/before runs event/language (999) and event/theme (1000), where the admin event/theme only selects the template engine and does not account for the theme editor. In the 4.1 admin, these are event/ (0) and event/language (999).
A few more practical tips:
- Do not attach a handler to
view/*/beforewithout need. It will fire for every page template. In 4.1, each product card in a list is rendered by a separateproduct/thumbtemplate, so in a category with 20 products the handler will run at least 20 times just for the cards. - Check the module status at the start of the handler. A disabled module does not disable its events.
- Test with the theme that is installed in the store. Third-party themes often have their own template copies, and an edit verified on the standard theme may not find its string there.
- If you need to change the core PHP code rather than a template, a template event will not help; for code modifications, see the blog: OCMOD in OpenCart: code edits without changing system files.

Summary
view/…/beforegives access to$route,$dataand$code, and in 4.1 also to$output;view/…/aftergives access to the finished HTML.- Variables in
$dataare the safest technique; module language strings loaded up to priority 998 will be added to the template by the core itself. - In 3.0, perform the
$routesubstitution with a priority below 500 so thatevent/themefinds your file; in 4.1 the extension template is located inextension/.{код}/ catalog/ view/ template/ - Perform the
$codeedit with a priority above 500 so you do not lose it to the theme editor, and verify that the string to replace was found. - In 3.0, do not return values from the handler without need; in 4.1, the return value is ignored.
The next step is intercepting models via model/*/after, and when events are not enough, OCMOD. The materials are collected in the section Events and OCMOD; the syntax of templates themselves is described in the article Twig in OpenCart, and preparing $data in the controller is covered in the article OpenCart controller.