---
title: Asignacion de variables Smarty en modulos
section: front
slug: smarty-assign
description: "Como asignar variables PHP a templates Smarty en modulos PrestaShop: assign(), fetchTemplate(), variables globales, escape de HTML y mejores practicas."
keywords: prestashop smarty assign variable template modulo php escape html fetch display
last_updated: 2024-12-01
source_url: "https://ayudaprestashop.es/front/smarty-assign"
---

# Asignacion de variables Smarty en modulos

> Como asignar variables PHP a templates Smarty en modulos PrestaShop: assign(), fetchTemplate(), variables globales, escape de HTML y mejores practicas.

Smarty es el motor de plantillas del Front Office de PrestaShop. Los modulos asignan variables PHP a los templates con `$this->context->smarty->assign()` y luego renderizan con `$this->display()` o `$this->fetch()`.

## assign() y assignArray()

*Asignar variables individuales y en bloque*

```php
<?php

// ── VARIABLE INDIVIDUAL ──
$this->context->smarty->assign('product_name', $product->name[$idLang]);
$this->context->smarty->assign('price', Tools::displayPrice($product->price));
$this->context->smarty->assign('is_logged', $this->context->customer->isLogged());

// ── MULTIPLE EN ARRAY (recomendado — una sola llamada) ──
$this->context->smarty->assign([
    'product'       => $product,
    'product_name'  => $product->name[$idLang],
    'category'      => $category,
    'items'         => $this->getModuleItems(),
    'module_dir'    => $this->_path,
    'module_name'   => $this->name,
    'ajax_url'      => $this->context->link->getModuleLink($this->name, 'ajax'),
    'token'         => Tools::getToken(false),
]);

// ── assignArray (equivalente a assign con array) ──
$this->context->smarty->assignArray([
    'var1' => 'valor1',
    'var2' => 'valor2',
]);
```

## Variables disponibles globalmente

| Variable Smarty | Descripcion | Ejemplo de uso |
| --- | --- | --- |
| {$cart} | Carrito actual | {$cart.products\|count} productos |
| {$customer} | Cliente logueado | {$customer.firstname} |
| {$currency} | Moneda activa | {$currency.sign} |
| {$language} | Idioma activo | {$language.iso_code} |
| {$shop} | Datos de la tienda | {$shop.name} |
| {$urls} | URLs del sitio | {$urls.base_url} |
| {$page} | Datos de la pagina actual | {$page.meta.title} |
| {$link} | Objeto Link | {$link->getProductLink(42)} |
| {$static_token} | Token de sesion | Para formularios |
| {$breadcrumb} | Miga de pan | {foreach $breadcrumb.links as $b} |

## Renderizar templates desde el modulo

*fetch() vs display() — renderizar templates Smarty*

```php
<?php

// ── DESDE UN FRONTCONTROLLER ──

// $this->display() muestra el template directamente (output buffer)
// La ruta se define en $this->template
$this->template = 'module:mymodule/views/templates/front/mypage.tpl';
// (initContent() la usa automaticamente)

// ── DESDE UN HOOK DE DISPLAY ──

// $this->fetch() devuelve el HTML como string (para return en hooks)
$html = $this->fetch('module:mymodule/views/templates/front/block.tpl');
return $html;

// Alternativa con ruta absoluta
$html = $this->context->smarty->fetch(
    _PS_MODULE_DIR_ . 'mymodule/views/templates/front/block.tpl'
);

// ── PATHS VALIDOS ──
// module:mymodule/views/templates/front/page.tpl  (recomendado)
// module:mymodule/views/templates/hook/nav.tpl
// Absoluto: _PS_MODULE_DIR_ . 'mymodule/views/templates/front/page.tpl'
```

## Escape de HTML — seguridad

*Escape correcto en templates Smarty — evitar XSS*

```smarty
{* CORRECTO: escapar variables de usuario *}
<h1>{$product_name|escape:'html'}</h1>
<p>{$description|escape:'html'}</p>

{* INCORRECTO: sin escape (vulnerable a XSS) *}
{* <h1>{$user_input}</h1> *}

{* HTML seguro — solo cuando el contenido viene del BO y ya esta saneado *}
<div class="description">{$html_description nofilter}</div>

{* URLs — usar escape:'htmlall' para atributos href *}
<a href="{$url|escape:'htmlall'}">{$title|escape:'html'}</a>

{* Para JavaScript — escape JSON *}
<script>
  var data = {$items|json_encode|escape:'javascript'};
</script>

{* Forma mas segura de pasar datos a JS *}
<script>
  var MyModule = {literal}{{/literal}
    ajaxUrl: '{$ajax_url|escape:"javascript"}',
    token: '{$token|escape:"javascript"}'
  {literal}}{/literal};
</script>
```

## Variables en hooks (display hooks)

*Asignar y renderizar en hooks de display*

```php
<?php

/**
 * Hook de display: asignar variables y devolver HTML del template.
 * $params contiene datos contextuales del hook.
 */
public function hookDisplayProductAdditionalInfo(array $params): string
{
    $product   = $params['product'];  // objeto o array segun el hook
    $productId = (int) ($product['id'] ?? $product->id ?? 0);

    // Comprobar si hay datos que mostrar
    $data = $this->getProductData($productId);
    if (empty($data)) {
        return ''; // No mostrar nada si no hay datos
    }

    $this->context->smarty->assign([
        'mymodule_data'   => $data,
        'mymodule_url'    => $this->context->link->getModuleLink($this->name, 'detail', ['id' => $productId]),
        'mymodule_token'  => Tools::getToken(false),
    ]);

    return $this->fetch('module:' . $this->name . '/views/templates/hook/product-info.tpl');
}
```


---

*Fuente: [https://ayudaprestashop.es/front/smarty-assign](https://ayudaprestashop.es/front/smarty-assign). Version Markdown generada automaticamente para consumo por LLMs.*
