LogoLogo
Homepage
  • Documentations for PrestaShop 1.5
  • English documentation 1.5
    • About PrestaShop 1.5
    • New features in PrestaShop 1.5
    • Getting Started
      • What you need to get started
      • Installing PrestaShop
      • Installing PrestaShop using the command line
      • Updating & Uninstalling
      • Misc. information
    • Updating PrestaShop
      • Automatic update
      • Manual update
      • Making and restoring your own backup
      • In case of issues
    • User Guide
      • Training
      • Customizing your shop
      • Browsing the front-office
      • Connecting to the PrestaShop back-office
      • First steps with PrestaShop 1.5
      • Adding Products and Product Categories
      • A Look Inside the Catalog
      • Managing Orders
      • Managing Customers
      • Creating Price Rules and Vouchers
      • Managing Shipping
      • Understanding Local Settings
      • Managing Modules and Themes
      • Making the Native Modules Work
      • Understanding the Preferences
      • Understanding the Advanced Parameters
      • Administering the Back-Office
      • Understanding Statistics
      • Advanced Stock Management
      • Managing Multiple Shops
    • Developer Guide
      • Developer tutorials
        • Using the PrestaShop Web Service
          • Webservice one-page documentation
          • Chapter 1 - Creating Access to Back Office
          • Chapter 2 - Discovery - Testing access to the web service with the browser
          • Chapter 3 - First steps - Access the Web service and list client
          • Chapter 4 - Retrieve Data - Retrieving a Client
          • Chapter 5 - Modification - Update client
          • Chapter 6 - Creation - Remote Online Form
          • Chapter 7 - Removal - Remove customer accounts from the database
          • Chapter 8 - Advanced Use
          • Chapter 9 - Image management
          • Chapter 10 - Price management
          • Cheat-sheet - Concepts outlined in this tutorial
          • Web service reference
        • Helpers
          • HelperForm
          • HelperOptions
          • HelperList
          • Using helpers to overload a back-office template
        • New Developers Features In PrestaShop 1.5
        • Using the Context Object
        • DB class best practices
        • Public and overloadable methods
        • Overriding default behaviors
        • Using addJquery(), addJqueryPlugin() and addJqueryUI()
        • Handling special characters in links
        • Auto-updating modules
        • Front-Office Controllers
        • Controllers correspondence table
        • Specifics of multistore module development
        • Developer tips and tricks
        • PrestaShop's developer tools
        • Using the backward compatibility toolkit
      • Fundamentals
      • Coding Standards
      • Setting up your local development environment
      • Diving into PrestaShop Core development
      • Creating a PrestaShop module
      • Creating a front-office module
      • Creating a module with both front-end and back-end controllers
      • Hooks in PrestaShop 1.5
      • Translations in PrestaShop 1.5
      • How to use the Forge to contribute to PrestaShop
      • How to write a commit message
      • Contributing code to PrestaShop
    • Designer Guide
      • Theme development fundamentals
      • Integrating content in a page using hooks
      • Characteristics of a front-office theme
      • Characteristics of a back-office theme
      • Creating your own theme
      • Theme templates and Smarty
      • Using jQuery and Ajax
      • Best practices
      • Designer tutorials
        • Changes in version 1.5 which impact theme development
        • Changing a 1.4 theme to support gift products
        • Implementing layered navigation in a theme
    • System Administrator Guide
    • Merchant's Guide
      • Our advices
      • Sample price rules
    • FAQ
      • Using PrestaShop with WordPress
    • Troubleshooting
  • Documentation française 1.5
    • À propos de PrestaShop 1.5
    • Nouveautés de PrestaShop 1.5
    • Guide de démarrage
      • Ce dont vous avez besoin
      • Installer PrestaShop
      • Installer PrestaShop en ligne de commande
      • Mettre PrestaShop à jour
      • Informations diverses
    • Guide de mise à jour
      • Mise à jour automatique
      • Mise à jour manuelle
      • Faire une sauvegarde et la restaurer
      • En cas de problème
    • Guide de l'utilisateur
      • Formations
      • Personnaliser votre boutique
      • Parcourir le front-office
      • Se connecter au back-office de Prestashop
      • Premiers pas avec PrestaShop 1.5
      • Ajouter des produits et des catégories de produits
      • Un aperçu du catalogue
      • Gérer les commandes
      • Gérer les clients
      • Mettre en place des promotions
      • Gérer les transporteurs
      • Comprendre les réglages locaux
      • Gérer les modules et les thèmes
      • Configurer les modules natifs
      • Comprendre les préférences
      • Comprendre les paramètres avancés
      • Administrer le back-office
      • Comprendre les statistiques
      • Gestion avancée des stocks
      • Gérer plusieurs boutiques
    • Guide du développeur
      • Fondamentaux
      • Norme de développement
      • Mettre en place votre environnement de développement
      • Plonger dans le développement PrestaShop
      • Créer un module PrestaShop
      • Les hooks de PrestaShop 1.5
      • Les traductions dans PrestaShop 1.5
      • Comment utiliser la Forge pour contribuer à PrestaShop
      • Comment écrire un descriptif de modification
    • Guide de l'intégrateur
      • Fondamentaux de la création de thème
      • Intégrer du contenu dans une page à l'aide de hooks
      • Caractéristiques d'un thème front-office
      • Caractéristiques d'un thème back-office
      • Template de thème et Smarty
      • Utiliser jQuery et Ajax
      • Bonnes pratiques
    • Guide de l'administrateur système
    • Guide du vendeur
      • Exemples de promotions
      • Nos bons conseils
    • Questions fréquentes
    • Dépannage
  • Documentación española 1.5
    • Acerca de PrestaShop 1.5
    • Introducción
      • Lo que necesita para empezar
    • Guía del usuario
      • Formación
      • Personalización de su tienda
      • Exploración del front-office
      • Conexión al back-office de PrestaShop
      • Primeros pasos con PrestaShop 1.5
      • Añadir productos y categorías de productos
      • Una mirada interna al catálogo
      • Gestionar pedidos
      • Gestionar clientes
      • Crear reglas de precios y cupones
      • Gestionar el transporte
      • Comprender la Configuración Local
      • Gestionar módulos y temas
      • Configurar los Módulos Nativos
      • Comprender las Preferencias
      • Comprender los Parámetros avanzados
      • Administrar el Back-Office
      • Comprender las estadísticas
      • Gestión avanzada de stock
      • Gestionar varias tiendas
    • Guía del Desarrollador
      • Tutoriales para Desarrolladores
        • Uso del Web Service de Prestashop
          • Capítulo 1 - Creación de acceso al Back Office
  • Документация на русском языке 1.5
    • Информация о PrestaShop 1.5
    • Новые функции в PrestaShop 1.5
    • Приступая к работе
      • Что нужно чтобы приступить к работе
      • Установка PrestaShop
      • Установка PrestaShop при помощи командной строки
      • Обновление и удаление PrestaShop
      • Прочая информация
    • Руководство пользователя
      • Обучение
      • Настройка вашего магазина
      • Изучение публичной части сайта
      • Бэк-офис PrestaShop
      • Первые шаги в PrestaShop 1.5
      • Добавление товаров и товарных категорий
      • Внутри каталога
      • Управление заказами
      • Работа с клиентами
      • Создание правил ценообразования корзины и ваучеров
      • Управление доставкой
      • Ориентация в локальных настройках
      • Управление модулями и темами
      • Настойка встроенных модулей
      • Ориентация в настройках
      • Ориентация в расширенных параметрах
      • Администрирование Back-Office
      • Ориентация в статистике
      • Расширенное управление запасами
      • Управление мультимагазином
Powered by GitBook
On this page
  • Theme templates and Smarty
  • Basic principles
  • Advanced uses

Was this helpful?

  1. English documentation 1.5
  2. Designer Guide

Theme templates and Smarty

PreviousCreating your own themeNextUsing jQuery and Ajax

Last updated 4 years ago

Was this helpful?

Table of contents

/*<![CDATA[*/ div.rbtoc1597308501367 {padding: 0px;} div.rbtoc1597308501367 ul {list-style: disc;margin-left: 0px;} div.rbtoc1597308501367 li {margin-left: 0px;padding-left: 0px;} /*]]>*/

Theme templates and Smarty

Smarty is a PHP template engine that is sturdy, fast, easy to learn and use, and has a clean and compact design-dedicated syntax. It helps building a much simpler HTML code, and works by compiling then caching each page.

Basic principles

Delimiters

Delimiters make it possible for the template engine to "recognize" Smarty calls within a template. The delimiters used by Smarty are curly braces: {smarty_call}

If you need to use actual curly braces within your template code, Smarty has special calls for you: {redelim} for a left curly brace ({), and {rdelim} for a right curly brace (}).

Comments

As with any scripting or programming language, you can put comments within your template code, and the template engine will not parse them.

Comments use regular delimiters, along with opening and closing * characters:

{* One-line comment. *}

{* 
Multiple
lines
comment.
*}

{* Comment for Smarty {$code} *}

Variables

Just as in PHP, variable are represented by a dollar sign followed by the name of the variable. Putting a variable directly within a Smarty delimiter means that you want to display the variable as-is. For instance, {$foo} is the Smarty equivalent of PHP's echo $foo;.

You can also apply modifiers to your variables:

{* Displaying the content of the variable in lowercase. *}
{$foo|lower}
    
{* Displaying the content of the variable after replacing one word with another. *}
{$foo|replace:'bar':'baz'}
    
{* Example of "chaining" modifiers.	 *}
{$foo|lower|capitalize|truncate:10:'...'}

Conditionals

Smarty has a conditional if / else / elseif system:

{if $coffee == 'good'}
  {* Happy coder *}
{elseif $coffee == 'very good'}
  {* Very happy coder *}
{else}
  {* Grumpy coder *}
{/if}

Loops

Smarty supports two loops: section and foreach. You can use iterators, and even the foreachelse conditional:

<?php
  $items_list = array( 23 => array('no' => 2456, 'label' => 'Salad'), 96 => array('no' => 4889, 'label' => 'Cream') );
  $smarty->assign('items', $items_list);
?>
<ul>
{foreach from=$items key=myId item=i}
  <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li>
{/foreach}
</ul>

You can learn more on each loop on their respective pages on the official website:

File inclusion

You can easily include a template file into another using the include, extends or block functions. Thanks to inheritance, file inclusion can impact many templates at a time.

The assignation method takes two mandatory arguments:

  • file: the name of the template file to include.

  • assign: the name of the variable that the output of include will be assigned to.

Here are a couple examples:

{* Including a file. *}
{include file='steps.tpl'}
   
{* Placing the included content in a variable, then display the variable.	 *}
{include file='text.tpl' assign='MyText'}
{$MyText}

Demonstration of inheritance with extends and block:

{* Filename: parent.tpl *}
<html>
<head>
<title>{block name="title"}Default Title{/block}</title>
...
{block name="title"}New Title{/block}
</head>
</html>

{* Filename: child.tpl *}
{extends file='parent.tpl'}
{block name='title'}New Page Title{/block}

That last example uses the block function, which is designed to define a named area of template source for template inheritance.

You can learn more about template inheritance and each inclusion function on their respective pages on the official website:

Debug function

The complete set of internal processes from a Smarty template can be displayed when the page is displayed.

During theme development, this can be done for each page load by editing the /config/smarty.config.inc.php file and editing the $smarty->debugging value:

$smarty->debugging = true;

Once the theme is on a production site, you can enable the debug function by adding the {DEBUG} directive in the template file.

You can also manage the debug function directly from PrestaShop: in the "Advanced Parameters" menu, in the "Maintenance" page, change the "Debug console" option to your liking.

Advanced uses

Captures

The capture function makes it possible to retrieve the output of an template without displaying it. For instance: {capture name="myCapture'} ... {/capture}

In order to use the content, you must call the $smarty super-variable: $smarty.capture.myCapture

Do not forget to test for the capture's existence before using it:

{if $smarty.capture.<name>} or {if isset($smarty.capture.<name>}

The capture function is also able to auto-assign a variable:

{capture name='myCapture' assign='myVar'}
   ...
{/capture}
{* Then, in order to use the content, call the $myVar variable. *}

Assigning variables

It is possible to assign a variable into a template file (view), using the assign function:

{assign var='myVar2' value='My value'}

{* Will display "My value". *}
{$myVar2}

The $smarty variable

$smarty is a so-called super-variable. It makes it possible to retrieve some useful information:

  • capture values: $smarty.capture.myVariable

  • GET values: {$smarty.get.<name>}

  • POST values: {$smarty.post.<name>}

  • Current timestamp: {$smarty.now}, or with customized formatting {$smarty.now|date_format:'%d-%m-%Y %H:%M:%S'}

  • PHP constants: {$smarty.const.<constant name>}

In Smarty 2, $smarty could be used with foreach:

When the loop is defined as: {foreach from=$myarray key="mykey" item="myitem"} ...you can perform a $smarty.foreach.name.property call

Since PrestaShop 1.5, it is recommended to only rely on the Smarty 3 syntax. Therefore, $smarty.foreach.varName.property call must be replaced by the $varName@property equivalent call.

Literals

The literal tag makes it possible for a data block to be used as-is, literally, without Smarty trying to interpret it:

{literal}
<script type="text/javascript">
  function myFonction()
  {
    ...
  }
</script>
{/literal}

Functions

Smarty functions do not use the $ prefix, as do variables: {debug}, {rdelim}, {ldelim}, ...

They can accept arguments: {include file='<name of the file>'}

The structure of a function call is thus: {nameOfTheFunction arg1='...' arg2='...'}

You cannot use modifiers on functions. For instance, {nameOfTheFunction arg1='...' |lower} will not work as expected.

You can learn more about Smarty functions on the official website:

Plugins

Smarty plugins makes it possible to easily extend the standard behavior. They are written in PHP.

For instance, PrestaShop has a Smarty plugin that creates a specific function to handle translatable strings: {l}

First, in a theme:

{l s='Hello dear viewer'}

And in a module (even if overridden!):

{l s='Hello dear view' mod='myModule'}

Smarty Don'ts with PrestaShop

A few things that you should expressly avoid when using Smarty:

  • Do not make direct call PrestaShop's constants. Most particularly, do not even use {$smarty.const._DB_PASSWD_}, for obvious reasons.

  • Do not override PrestaShop's assigned variables.

  • Do not make the code needlessly hard to read. For instance, refrain from making include calls from within an already included file.

  • Do not make direct PHP calls. For instance, do not use {php} // PHP code {/php}

You can learn more by going to its official website:

You can get a complete list of the available modifiers on the official website:

You can learn more about the various conditionals on the official website:

You can learn more about the debug function on the official website:

You can learn more about the capture function on the official website:

You can learn more about the assign function on the official website:

You can learn more about the $smarty variable on the official website:

You can learn more about the literal function on the official website:

You can learn more about Smarty plugins on the official website:

http://www.smarty.net/
http://www.smarty.net/docsv2/en/language.modifiers.tpl
http://www.smarty.net/docsv2/en/language.function.if.tpl
http://www.smarty.net/docs/en/language.function.section.tpl
http://www.smarty.net/docs/en/language.function.foreach.tpl
http://www.smarty.net/docs/en/advanced.features.template.inheritance.tpl
http://www.smarty.net/docs/en/language.function.include.tpl
http://www.smarty.net/docs/en/language.function.extends.tpl
http://www.smarty.net/docs/en/plugins.block.functions.tpl
http://www.smarty.net/docs/en/language.function.debug.tpl
http://www.smarty.net/docs/en/language.function.capture.tpl
http://www.smarty.net/docs/en/language.function.assign.tpl
http://www.smarty.net/docs/en/language.variables.smarty.tpl
http://www.smarty.net/docs/en/language.function.literal.tpl
http://www.smarty.net/docs/en/language.syntax.functions.tpl
http://www.smarty.net/docs/en/language.builtin.functions.tpl
http://www.smarty.net/docs/en/language.custom.functions.tpl
http://www.smarty.net/docs/en/plugins.tpl
Theme templates and Smarty
Basic principles
Delimiters
Comments
Variables
Conditionals
Loops
File inclusion
Debug function
Advanced uses
Captures
Assigning variables
The $smarty variable
Literals
Functions
Plugins
Smarty Don'ts with PrestaShop