Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 30 ยท Front Office

Smarty Templates and Theme Integration

Learn Smarty basics for PrestaShop modules: assign and fetch, escaping, template resolution, theme overrides of module templates, hooks in themes and child themes.

Everything a customer sees on the storefront passes through Smarty, the template engine that PrestaShop's front office has used for years. A hook method or a front controller prepares data in PHP, then asks Smarty to merge that data into a .tpl file and produce HTML. The theme decides how the page looks, but your module ships its own templates, and the theme is allowed to replace them.

This lesson teaches the Smarty syntax you will use daily, how data gets from PHP into a template, how PrestaShop finds the right file (module, theme, parent theme), why escaping matters, and how theme.yml and child themes fit in. You have already used fetch() and setTemplate() in Common Front Office Hooks and Module Front Controllers.

Smarty and the theme engine need a running shop and cannot execute here. The syntax and files appear as read-only code. The runnable examples are small PHP stand-ins that copy the behavior (variables, loops, escaping, file lookup) so you can see the logic. They are not Smarty itself and support only a fraction of it.

From PHP to template

The module prepares variables with assign() and then renders a file:

PHP
<?php
// read-only: inside a module class
public function hookDisplayProductAdditionalInfo(array $params): string
{
    $this->context->smarty->assign([
        'badge_label' => $this->l('Free returns'),
        'badge_items' => [
            ['name' => 'Returns', 'days' => 30],
            ['name' => 'Exchanges', 'days' => 60],
        ],
    ]);

    return $this->fetch('module:acmebadge/views/templates/hook/badge.tpl');
}

fetch() renders the template and returns the HTML string, which is exactly what a display hook must return. In a front controller you use setTemplate() instead and PrestaShop renders it inside the page layout. Older modules use $this->display(__FILE__, 'badge.tpl'); it still works and looks for the file in views/templates/hook/, but new code should use the module: form.

Assign only what the template needs. Everything assigned is visible to every template rendered later in that request, so use specific names (badge_label, not label) to avoid clobbering variables other modules or the theme use.

Smarty syntax you need

Smarty tags sit in curly braces. The ones you will meet in almost every template:

SMARTY
{* This is a comment: it is removed from the output. *}

{* Print a variable. Arrays use dots, objects use ->. *}
<h3>{$badge_label}</h3>
<p>{$product.name} costs {$product.price}</p>
<p>{$customer.firstname}</p>

{* Conditions *}
{if $badge_items}
  <ul>
    {foreach from=$badge_items item=entry}
      <li>{$entry.name}: {$entry.days} days</li>
    {/foreach}
  </ul>
{elseif $product.on_sale}
  <p>On sale.</p>
{else}
  <p>No badge.</p>
{/if}

{* Translate a string; "d" is the translation domain *}
<button>{l s='Save for later' d='Modules.Acmebadge.Shop'}</button>

{* Include another template *}
{include file='module:acmebadge/views/templates/hook/_row.tpl' row=$entry}

{* Render everything that modules put into a hook *}
{hook h='displayAcmeBadgeExtra' product=$product}

Some more details:

  • {foreach from=$list item=x key=k} loops; the newer {foreach $list as $x} form also works.
  • {assign var='total' value=$a + $b} or {$total = $a + $b} creates a variable.
  • Modifiers transform a value with a pipe: {$text|upper}, {$name|truncate:20:'...'}, {$list|count}.
  • {extends file='...'} and {block name='...'} are how themes build layouts: a child template fills named blocks of a parent layout.
  • Built-in template variables in the storefront include $urls (for example $urls.pages.cart, $urls.base_url), $link (the link builder) and $static_token for forms.
  • {widget name='ps_shoppingcart'} renders a module that implements the widget interface; it is how themes place modules without a hook.

Keep logic out of templates. A template can loop and branch, but computing prices, querying the database or calling services belongs in PHP.

Escaping: the template is where XSS happens

Product names, customer messages and search terms can contain <script>. If a template prints them raw, a visitor can inject code into other visitors' pages (cross-site scripting, XSS). Two rules:

  1. Escape by default. PrestaShop 1.7 and later turn on Smarty's automatic HTML escaping for the storefront, which is why trusted HTML in the core themes is printed with the nofilter flag. Do not rely on your memory of which setting is on: when you print any value that came from a user or a database, make sure it is escaped, and test it with a name such as <b>x</b>.
  2. Use nofilter only for HTML you control, such as a product description edited by the shop owner in a rich editor, and understand that this bypasses protection.
SMARTY
{* Escaped automatically on 1.7+ storefronts; the explicit modifier is harmless and works everywhere *}
<p>{$query|escape:'html':'UTF-8'}</p>

{* Trusted HTML only *}
<div class="description">{$product.description nofilter}</div>

When you put values in HTML attributes or JavaScript, escape for that context, and prefer data- attributes plus JSON encoding in PHP over building scripts by hand. Security in Modules goes deeper.

Stand-in: a tiny template engine

This engine supports {$var} with dots and a few modifiers, /, , {l s=''}, {hook h=''}, {include file=''} and comments. Variables are escaped unless followed by nofilter. It is about 100 lines because it ignores nearly everything real Smarty does, but it shows the core ideas: variables in a scope, blocks, escaping by default.

PHP Stand-in: a tiny Smarty-like engine

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.

In the output, the malicious product name and search query appear as harmless escaped text (&lt; and &gt; instead of angle brackets; the product name is also upper-cased by the upper modifier), while $description nofilter keeps its <em> tag. That difference between "escaped by default" and "explicitly trusted" is the most important Smarty habit.

Template resolution: who wins?

When you render module:acmebadge/views/templates/hook/badge.tpl, PrestaShop looks for the file in this order and uses the first one it finds:

  1. The active theme override: themes/<theme>/modules/acmebadge/views/templates/hook/badge.tpl.
  2. If the theme is a child theme, the same path in the parent theme (themes/classic/modules/...).
  3. The module's own file: modules/acmebadge/views/templates/hook/badge.tpl.

Theme templates themselves (the pages, such as templates/catalog/product.tpl) are looked up in the active theme first and then in its parent. So a merchant or designer can change your module's HTML without editing the module: they copy the file into their theme and edit the copy. That is good for them, and it is a reason to keep your templates small, with stable variable names, because their copy will not receive your future improvements automatically. Mention changes in your changelog.

flowchart TD
    A["fetch module:acmebadge/.../badge.tpl"] --> B{"File in<br/>themes/child/modules/acmebadge/...?"}
    B -->|"yes"| Z["Use it"]
    B -->|"no"| C{"File in<br/>themes/classic/modules/acmebadge/...?"}
    C -->|"yes"| Z
    C -->|"no"| D["Use modules/acmebadge/views/templates/hook/badge.tpl"]
    D --> Z

Child theme first, then the parent theme, finally the module's own template.

Stand-in: resolving templates

This stand-in lists the files that exist in a virtual file system and prints which candidate wins for three situations. It also renders the winner with a plain {$label} replacement so you see the visible effect of an override.

PHP Stand-in: theme override resolution

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 last scenario shows the benefit of a child theme: it only contains the files you changed, and everything else falls through to the parent.

theme.yml and child themes

Every theme has a config/theme.yml file that describes it. This is a short excerpt of a child theme (read-only):

YAML
# themes/mychild/config/theme.yml
parent: classic
name: mychild
display_name: My Child Theme
version: 1.0.0
author:
  name: "Acme Studio"
  email: "[email protected]"

meta:
  compatibility:
    from: 8.0.0
    to: ~

assets:
  css:
    all:
      - id: mychild-custom
        path: assets/css/custom.css
        media: all
        priority: 1000
  js:
    all:
      - id: mychild-custom
        path: assets/js/custom.js
        position: bottom
        priority: 1000

global_settings:
  hooks:
    modules_to_hook:
      displayProductAdditionalInfo:
        - acmebadge
  • parent: classic makes this a child theme: it inherits every template and asset from the parent, and any file with the same path in the child wins. Always customize a child theme instead of editing a parent, so updates to the parent do not erase your work.
  • assets registers theme CSS and JavaScript the same way a module registers them in code, with ids, paths, media or position, and priorities.
  • global_settings.hooks.modules_to_hook lists which modules the theme wants attached to which hooks when the theme is enabled. The theme still needs a {hook h='displayProductAdditionalInfo'} call in a template for any output to appear.
  • meta.compatibility states the PrestaShop versions the theme supports.

Hooks in themes

A theme places a hook with {hook h='displayName'} in a template (the layout file, a partial, or a page). Whatever the registered modules return is printed there. So a designer controls where a hook is rendered, and a module developer controls what it returns. If you need a spot that does not exist, you cannot add it from a module: the theme must call the hook. For that reason, a module meant for many themes should document which hook it needs and what a theme should add, or offer a alternative.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call renders a module's Smarty template and returns the HTML as a string?

    fetch() renders the template with the assigned variables and returns the result. assign() only prepares variables.
  2. 2. A theme contains themes/classic/modules/acmebadge/views/templates/hook/badge.tpl. Which file is used for the module's hook output when classic is active?

    A theme override takes precedence over the module's own template, which lets designers change the markup without editing the module.
  3. 3. When is it acceptable to print a value with nofilter?

    nofilter turns escaping off. Use it only for trusted HTML, such as a description edited by the shop owner, never for visitor input.
  4. 4. What does parent: classic in theme.yml mean?

    That is the child theme mechanism. The child holds only what it changes; everything else falls through to the parent.
  5. 5. Your module registered on displayProductAdditionalInfo, but nothing appears in the active theme. What should you check?

    A display hook only shows output where a template calls it. Themes decide which hooks they render.

Summary

  • PHP prepares data with smarty->assign(); fetch('module:...') returns HTML for hooks, and setTemplate() is used in front controllers.
  • Learn the core tags: {$var}, , , {l s=''}, , , , /, plus modifiers with |.
  • Keep logic in PHP, and make sure every user-supplied value is escaped; use nofilter only for trusted HTML.
  • Templates resolve child theme first, then parent theme, then the module's own file; designers override modules this way.
  • theme.yml describes a theme: parent, assets, compatibility and the modules to hook; a child theme keeps customizations separate from updates.
  • A theme chooses where a hook renders by calling {hook h='...'} in its templates.

Next, start working with data that lives in the database: ObjectModel and Entities.