No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Events and OCMOD

Event view in OpenCart: how to change a template via view/*/before in 3.0 and 4.1

Four ways to change an OpenCart template with an event without touching theme files: data, template substitution, Twig code editing, and editing ready-made HTML. For 3.0 and 4.1.

10 min read OC 3.0 OC 4.1

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->load->view('маршрут', $data). 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/product_form. Therefore, module triggers look like this:

  • catalog/view/product/product/before: only the product card on the storefront;
  • admin/view/catalog/product_form/before: the product form in the admin;
  • catalog/view/*/before: any storefront template (use with caution, see the last section).

Handler arguments are passed by reference:

ArgumentOpenCart 3.0OpenCart 4.1What you can do with it
&$routeyesyessubstitute a different template
&$datayesyesadd or change template variables
&$codeyesyespass Twig source code instead of a file
&$outputnoyesset 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->load->language(…), 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/view/theme/{тема}/template/. 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:

  1. Place the module file, for example, in catalog/view/theme/default/template/extension/module/my_product.twig.
  2. In the handler, assign $route = 'extension/module/my_product';.
  3. Register the event with sort_order lower than 500, so that event/theme looks 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/view/template/, and extension templates in extension/{код}/catalog/view/template/. The extension path registers startup/extension for each installed extension, so the route extension/my_module/module/my_product will point to the file extension/my_module/catalog/view/template/module/my_product.twig. 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->config->get('template_directory') . $route . '.twig', 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_replace will silently change nothing. Check strpos() 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/modification.view with priority 0 substitutes extension/ocmod/… if a copy of the template modified by OCMOD exists. Then the path DIR_TEMPLATE . $route will not exist, and the handler above will simply exit at the is_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:

TechniqueWhen it fitsRisk
Variables in $datathe theme already outputs the variable, or the template is yoursminimal
Replacing $routethe page needs to be rebuilt entirelytheme changes stop applying
Editing $codetargeted insertion into Twig markup with variablesdependence on the theme's markup
Editing $output in afterinsertion into finished HTML without Twig logicdependence 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/config/catalog.php and system/config/admin.php 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/modification.view (0) and event/language (999).

A few more practical tips:

  • Do not attach a handler to view/*/before without need. It will fire for every page template. In 4.1, each product card in a list is rendered by a separate product/thumb template, 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.
Design → Theme Editor: the template version saved here is substituted into $code with priority 500
Design → Theme Editor: the template version saved here is substituted into $code with priority 500 · OpenCart 4.1.0.4

Summary

  • view/…/before gives access to $route, $data and $code, and in 4.1 also to $output; view/…/after gives access to the finished HTML.
  • Variables in $data are 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 $route substitution with a priority below 500 so that event/theme finds your file; in 4.1 the extension template is located in extension/{код}/catalog/view/template/.
  • Perform the $code edit 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.

FAQ

Can you change an email or printed invoice template with a view event?
Yes, they are also rendered via $this->load->view(): the admin invoice has the route sale/order_invoice, and storefront emails are in mail/. The route of a specific template can be found in the load->view call in the corresponding controller.
Why are changes made via $code not visible after refreshing the page?
Most often the handler has a priority below 500, and event/theme overwrote $code with the version from the theme editor, or the string to replace was not found in the active theme's template. Check sort_order under Extensions → Events and log the strpos result.
Do you need to clear the Twig cache after changing handler logic?
Usually not: the renderer works with auto_reload, and a changed $code produces a different cache key. If something looks outdated, clear the template subdirectory in the OpenCart cache directory.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.