Configurar Smarty en Yii Framework

Publicado en Frameworks, Programación el 2 de May de 2009 por Manel Pérez Mata
Tags: , ,

Smarty Logo

Ayer os comentaba como instalar Yii desde 0. La necesidad de poder añadirle Smarty a este Framework, me hizo dar varias vueltas por Google para ver si alguien lo había resuelto, y después de un rato, llegué a la conclusión de que hasta la fecha, nadie lo había publicado en la red.

Así que, me puse manos a la obra y generé esta pequeña extensión para poder utilizar este gestor de plantillas con Yii. El código creado es:

CSmartyViewRenderer.php

  1. <?php
  2. /**
  3.  * CSmartyViewRenderer class file.
  4.  *
  5.  * @author Manel Pérez
  6.  * @license http://www.yiiframework.com/license/
  7.  */
  8.  
  9. /**
  10.  * CSmartyViewRenderer implements a view renderer that allows users to use a template syntax similar to SMARTY templates.
  11.  *
  12.  * To use CSmartyViewRenderer, configure it as an application component named "viewRenderer" in the application configuration /protected/config/main.php
  13.  * <pre>
  14.  * array(
  15.  *     ‘components’=>array(
  16.  *         ……
  17.  *         ‘viewRenderer’=>array(
  18.  *             ‘class’=>’CSmartyViewRenderer’,
  19.  *         ),
  20.  *     ),
  21.  * )
  22.  * </pre>
  23.  *
  24.  * @author Manel Pérez
  25.  * @version $Id: CSmartyViewRenderer.php 433 2009-03-16 22:59:17Z manel.perez $
  26.  * @package system.web.renderers
  27.  * @since 1.0
  28.  */
  29.  
  30. require_once "Smarty/Smarty.class.php";
  31.  
  32. class CSmartyViewRenderer extends CViewRenderer
  33. {
  34.     private $_input;
  35.     private $_output;
  36.     private $_sourceFile;
  37.     private $_smarty;
  38.  
  39.     function __construct()
  40.     {
  41.         $this->_smarty = new Smarty();
  42.     }
  43.  
  44.     /**
  45.      * Parses the source view file and saves the results as another file.
  46.      * This method is required by the parent class.
  47.      * @param string the source view file path
  48.      * @param string the resulting view file path
  49.      */
  50.     protected function generateViewFile($sourceFile,$viewFile)
  51.     {
  52.         $this->_output = $this->_smarty->get($sourceFile);
  53.  
  54.         file_put_contents($viewFile,$this->_output);
  55.     }
  56.  
  57.     /**
  58.      * Renders a view file.
  59.      * This method is required by {@link IViewRenderer}.
  60.      * @param CBaseController the controller or widget who is rendering the view file.
  61.      * @param string the view file path
  62.      * @param mixed the data to be passed to the view
  63.      * @param boolean whether the rendering result should be returned
  64.      * @return mixed the rendering result, or null if the rendering result is not needed.
  65.      */
  66.     public function renderFile($context,$sourceFile,$data,$return)
  67.     {
  68.         if(!empty($data)) {
  69.             if (is_array($data) || is_object($data)){
  70.                 foreach($data as $key=>$value) {
  71.                     if (is_array($value)) {
  72.                         if (is_a($value[0], "CActiveRecord")) {
  73.                             foreach ($value as $valKey=>$valRec) {
  74.                                 $att[] = $valRec->getAttributes();
  75.                             }
  76.  
  77.                             $this->_smarty->assign($key, $att);
  78.                         } else {
  79.                             $this->_smarty->assign($key, $value);
  80.                         }
  81.                     } else {
  82.                         $this->_smarty->assign($key, $value);
  83.                     }
  84.                 }
  85.             } else {
  86.                 //GENERIC Data assign
  87.                 $this->_smarty->assign("__DATA__", $data);
  88.             }
  89.         }
  90.  
  91.         if(!is_file($sourceFile) || ($file=realpath($sourceFile))===false)
  92.             throw new CException(Yii::t(‘yii’,‘View file "{file}" does not exist.’,array(‘{file}’=>$sourceFile)));
  93.         $viewFile=$this->getViewFile($sourceFile);
  94.         if(@filemtime($sourceFile)>@filemtime($viewFile))
  95.         {
  96.             $this->generateViewFile($sourceFile,$viewFile);
  97.             @chmod($viewFile,$this->filePermission);
  98.         }
  99.         return $context->renderInternal($viewFile,$data,$return);
  100.     }
  101. }
  102. ?>

¿Cómo hacemos que este código funcione? Aquí os dejo los pasos para hacer que Smarty y Yii vayan de la mano hacia un mundo de color y alegría:

  1. Descargamos el último código estable de la página oficial de Smarty y lo descomprimimos en la carpeta /path/to/application/framework/web/renders/
  2. Damos permisos 777 a la carpeta /path/to/framework/framework/web/renders/Smarty/templates_c
  3. Modificamos el fichero /path/to/framework/[ApplicationName]/protected/config/main.php añadiendo el siguiente código al array:
    1. ‘viewRenderer’=>array(
    2.             ‘class’=>‘CSmartyViewRenderer’,
    3.     ),
  4. Por último, le diremos a Yii qual es el nuevo render modificando el archivo /path/to/framework/framework/YiiBase.php, buscamos “‘CPradoViewRenderer’” y dejamos el código de la siguiente manera:
    1. //’CPradoViewRenderer’ => ‘/web/renderers/CPradoViewRenderer.php’,
    2. ‘CSmartyViewRenderer’ => ‘/web/renderers/CSmartyViewRenderer.php’,

Con esto, deberíamos tener funcionando Smarty en Yii… ahora nos queda modificar nuestros templates para que sigan la sintaxis propuesta por Smarty, y crear nuestros propios plugins que nos permitan interactuar con los helpers del framework.

Compártelo!! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Meneame
  • BarraPunto
  • Technorati
  • Google Bookmarks
  • Facebook
  • LinkedIn
  • del.icio.us
  • Digg
  • Reddit
  • Live-MSN
  • MySpace
  • TwitThis
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
Loading ... Loading ...

One Comment on “ Configurar Smarty en Yii Framework ”

Leave a Reply