Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 27 ยท MVC-L core

Twig Views and Language Files

Write OpenCart 4 views in Twig and keep text in language files. Learn variables, loops, conditions, text_ keys and why you must escape output yourself.

The V and the L of MVC-L finish the picture. A view is a Twig template that turns the data array from a controller into HTML. A language file is a PHP file that returns a list of strings, so the template never contains text meant for people. Together they let a store owner translate your extension without touching your templates, and let you change the layout without touching your logic.

This lesson shows how a controller hands data to a view, how language keys are named, what the Twig syntax looks like for output, loops and conditions, and the one security fact every OpenCart developer must remember: output in OpenCart templates is not escaped for you unless you escape it. The runnable stand-in is a small template engine that makes this visible.

From controller to template

You have already seen the controller side. It builds an array and asks the loader to render a template by route:

PHP
$data['heading'] = $this->language->get('heading_title');
$data['products'] = $products;   // array of arrays

return $this->load->view('extension/acme/module/hello_banner', $data);

The route extension/acme/module/hello_banner is resolved to a file in your extension, catalog/view/template/module/hello_banner.twig (in the storefront) or admin/view/template/module/hello_banner.twig (in the admin). A theme can provide its own copy of a template and win over yours; that is the subject of Themes and Frontend Customisation.

A matching storefront template could be:

TWIG
<div class="hello-banner">
  <h3>{{ heading }}</h3>
  {% if products %}
    <ul>
      {% for product in products %}
        <li><a href="{{ product.href }}">{{ product.name }}</a> - {{ product.price }}</li>
      {% endfor %}
    </ul>
  {% else %}
    <p>{{ text_empty }}</p>
  {% endif %}
</div>

The three Twig constructs you use all the time are:

Syntax Purpose
{{ value }} Print a value. Dots reach into arrays: product.name
{% if %} ... {% else %} ... {% endif %} Branch on a condition
{% for item in list %} ... {% endfor %} Repeat for each item

Twig has many more features (filters, macros, inheritance, {# comments #}), and OpenCart ships a recent Twig 3 release, but templates in OpenCart are deliberately plain. A template should contain presentation only. Compute prices, build links and format dates in the controller, then pass the finished strings in.

Language files

A language file returns nothing; it fills a $_ array. Here is the storefront file for our module:

PHP
<?php
// extension/acme/catalog/language/en-gb/module/hello_banner.php

// Heading
$_['heading_title'] = 'Hello Banner';

// Text
$_['text_empty']    = 'No products to show yet.';
$_['text_greeting'] = 'Welcome, %s!';

You load it in the controller with $this->load->language('extension/acme/module/hello_banner') and read a string with $this->language->get('text_empty'). In core OpenCart each string is assigned into $data explicitly, which keeps the template's inputs visible in one place.

The key names follow conventions that every OpenCart developer recognises:

  • heading_title: the page title.
  • text_*: any sentence or label, for example text_success.
  • entry_*: the label of a form field.
  • button_*: button captions.
  • help_*: tooltip texts.
  • tab_*, column_*, error_*: tabs, table headings and error messages.

Follow them. Store owners and translators read these files, and the admin relies on some keys (such as heading_title and text_extension) being present.

Language files also take placeholders. sprintf($this->language->get('text_greeting'), $name) fills in %s. Never glue translated fragments together with concatenation ('Welcome ' . $name), because word order differs between languages.

flowchart LR
    C["Controller"] -->|"load->language()"| L["Language file<br/>en-gb/module/x.php"]
    C -->|"data array"| T["Twig template<br/>x.twig"]
    L -->|"strings"| C
    T --> H["HTML"]

The controller reads strings from the language file and passes everything to the template as one data array.

Escaping is your job

Many template engines escape output automatically. OpenCart does not. Its Twig environment is set up without automatic escaping (check system/library/template/twig.php in your copy to confirm), which means {{ product.name }} prints the text exactly as it is. If that text contains <script>, the browser will run it.

So you escape in one of two places:

  1. In the template, with the escape filter: {{ product.name|escape }} (the short form |e works too).
  2. In the controller, with htmlspecialchars($value, ENT_QUOTES, 'UTF-8') before putting the value into $data.

Core OpenCart does a mix of both, and descriptions are special: the product description in the database is stored HTML-encoded, and controllers decode it with html_entity_decode() because store owners are allowed to write HTML there. Such trusted HTML is printed raw. The raw filter is not needed when autoescape is off, but writing |raw documents your intent in environments where it is on, and you should only ever use it for HTML you trust:

TWIG
<h3>{{ product.name|escape }}</h3>
<div class="description">{{ product.description|raw }}</div>

The pitfalls follow from that:

  • Forgetting |escape on a customer-controlled value (a name, a review, a search term, a coupon code) is a stored or reflected cross-site scripting hole.
  • Escaping twice shows &amp;lt; on the page. Escape once, as late as possible.
  • Escaping for the wrong context. escape is for HTML text. A value placed inside a <script> block or an onclick attribute needs JSON encoding (json_encode) with the right flags, and a URL needs rawurlencode. Prefer data attributes and {{ value|escape }} over inline JavaScript.
  • Using raw on admin-entered HTML is usually fine, but on shopper-entered text it never is.

Treat every value that originates outside your code as hostile until it has been escaped for the place where you print it. Cheap to do, expensive to forget.

The admin side

Admin templates follow the same rules, with more markup. A settings form in OpenCart 4 is a Bootstrap 5 form that is submitted with Ajax, so its template contains the form, a save button and an alert area:

TWIG
{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header"><div class="container-fluid">
    <h1>{{ heading_title }}</h1>
  </div></div>
  <div class="container-fluid">
    <form id="form-module" action="{{ save }}" method="post" data-oc-toggle="ajax">
      <label for="input-message" class="form-label">{{ entry_message }}</label>
      <input type="text" name="module_hello_banner_message"
             value="{{ module_hello_banner_message|escape }}" id="input-message" class="form-control"/>
      <button type="submit" class="btn btn-primary">{{ button_save }}</button>
    </form>
  </div>
</div>
{{ footer }}

The pieces header, column_left and footer are HTML strings produced by other controllers and passed in; they are intentionally printed as they are. The value of an input field, on the other hand, is escaped, because it comes from the database and may contain a quote that would break out of the attribute. The next chapter, Admin Settings Forms, builds this page completely.

A template engine to experiment with

The stand-in below is a tiny template engine written for this lesson. It supports {{ value }}, dotted names, the escape and raw filters, {% if %} with {% else %}, and {% for %}. Like OpenCart's Twig setup, it does not escape by default; you opt in with the filter. It is far simpler than real Twig, so use it to understand behaviour, not to learn Twig syntax details.

PHP A small template engine without autoescape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Seeing the escaping problem

The second stand-in feeds a hostile product name through two templates: one prints the value as it is, the other uses the escape filter. Compare the two lines of HTML the browser would receive.

PHP Unescaped versus escaped output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first line contains a real tag with a script handler. The second shows harmless text. In an attribute, escaping also protects the quotation marks that would otherwise end the attribute early.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should text that people read, like button captions, be stored?

    Language files keep text separate from layout, so the extension can be translated without editing templates.
  2. 2. In OpenCart 4's Twig setup, what happens to {{ product.name }} when the name contains a script tag?

    Automatic escaping is off, so escaping is the developer's responsibility.
  3. 3. Which prefix is conventional for the label of a form field in a language file?

    entry_ keys are the form labels; text_ is for general text, error_ for errors and help_ for tooltips.
  4. 4. Which template line is safest for a value coming from a customer review?

    Only an explicit escape makes the text safe in HTML. raw and plain output are unsafe, and inline script needs JSON encoding instead.

Summary

  • A controller builds a $data array and renders a .twig template with $this->load->view().
  • Language files fill $_[...] keys (heading_title, text_*, entry_*, button_*) read with $this->language->get().
  • Keep templates simple: print, if, for. Compute everything else in the controller.
  • OpenCart's Twig does not escape automatically: use |escape (or escape in the controller) for every untrusted value, and |raw only for HTML you trust.
  • Beware double escaping and the wrong context, such as inline JavaScript.

Next: Admin Settings Forms