Skip to content

08 modifiers smarty

Miguel92 edited this page Nov 29, 2026 · 1 revision

Modifiers Smarty Personalizados

BigBang Docs · Índice · Guía de estilo · Solución de problemas

Los modifiers se encuentran en app/Smarty/ y se usan automáticamente en los templates.

Modifier existente: abbr

Abrevia números grandes:

{$post->viewsCount|abbr}     {* 4800 → 4.8K *}
{$post->commentsCount|abbr}  {* 1200 → 1.2K *}
{$post->points|abbr}         {* 850 → 850 *}

Archivo: app/Smarty/modifier.abbr.php

Crear un nuevo modifier

Paso 1: Crear el archivo

Nombre del archivo: app/Smarty/modifier.{nombre}.php

<?php

/**
 * Smarty modifier: {$variable|nombre}
 *
 * @param string $value
 * @return string
 */
function smarty_modifier_nombre(string $value): string
{
    // Tu lógica aquí
    return strtoupper($value);
}

Paso 2: Usar en template

{$mi_variable|nombre}

Ejemplos útiles

Modifier str_limit (limitar caracteres)

<?php

function smarty_modifier_str_limit(string $value, int $limit = 100, string $suffix = '...'): string
{
    if (mb_strlen($value) <= $limit) {
        return $value;
    }
    return mb_substr($value, 0, $limit) . $suffix;
}

Uso: {$post->body|str_limit:200}

Modifier date_format (formatear fecha)

<?php

function smarty_modifier_date_format(int $timestamp, string $format = 'd/m/Y'): string
{
    return date($format, $timestamp);
}

Uso: {$post->createdAt|date_format:'d/m/Y H:i'}

Modifier capitalize_words (capitalizar cada palabra)

<?php

function smarty_modifier_capitalize_words(string $value): string
{
    return ucwords($value);
}

Uso: {$category->name|capitalize_words}

Modifier json_encode (para data attributes)

<?php

function smarty_modifier_json(?array $data): string
{
    return htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8');
}

Uso: <div data-items="{$items|json}">

Notas importantes

  • El nombre del archivo debe ser exactamente modifier.{nombre}.php
  • La función debe llamarse smarty_modifier_{nombre}
  • Smarty detecta los modifiers automáticamente al cargar el template
  • No necesitas registrarlos en ningún archivo de configuración

Clone this wiki locally