Smarty és un motor per a crear plantilles, és a dir és un framework que permet crear plantilles i presentacions per a aplicacions PHP.
Smarty proporciona als programadors i als dissenyadors web un conjunt d'eines que permeten automatitzar les tasques comunes relacionades amb la capa d'aplicació d'una aplicació.
Algunes aplicacions porten l'smarty com una llibreria més de l'aplicació. Típicament existeix una carpeta anomenada:
libs
On es col·loquen les llibreries. Per exemple l'aplicació webfaltes en algunes de les seves primeres versions tenia smarty instal·lat a:
libs/smarty
A la web d'smarty es pot descarregar la última versió (a --acacha 05:51, 28 feb 2010 (UTC) Smarty 2.6.26):
http://www.smarty.net/download.php
La podeu obtenir amb wget:
$ cd $ mkdir smarty $ cd smarty $ wget http://www.smarty.net/do_download.php?download_file=Smarty-2.6.26.tar.gz $ tar xvzf Smarty-2.6.26.tar.gz $ cd Smarty-2.6.26/
A l'arrel d'smarty hi ha fitxers de documentació (INSTALL, README, etc.) i una carpeta amb exemples (demo). Però el més important és troba a la carpeta libs. Per començar a treballar amb smarty utilitzareu un objecte que creareu a partir de la classe definida al fitxer:
libs/Smarty.class.php
Aquest tipus d'instal·lació es pot fer manual descarregant smarty de la web d'smarty o es pot utilitzar apt-get:
$ sudo apt-get install smarty
No sempre és te l'última versió però té tots els avantatges de instal·lar un paquet (p. ex. actualitzacions). La versió la podeu consultar amb:
$ sudo dpkg -l | grep smarty ii smarty 2.6.22-1ubuntu2 Template engine for PHP ii smarty-acl-render 2.6.7-1lenny1 Provide ACL based rendering for Smarty ii smarty-gettext 1.0b1-3 Gettext plugin enabling internationalization
Els fitxers instal·lats són:
$ dpkg -L smarty /. /usr /usr/share /usr/share/php /usr/share/php/smarty /usr/share/php/smarty/internals /usr/share/php/smarty/internals/core.assemble_plugin_filepath.php /usr/share/php/smarty/internals/core.assign_smarty_interface.php /usr/share/php/smarty/internals/core.create_dir_structure.php /usr/share/php/smarty/internals/core.display_debug_console.php /usr/share/php/smarty/internals/core.get_include_path.php /usr/share/php/smarty/internals/core.get_microtime.php /usr/share/php/smarty/internals/core.get_php_resource.php /usr/share/php/smarty/internals/core.is_secure.php /usr/share/php/smarty/internals/core.is_trusted.php /usr/share/php/smarty/internals/core.load_plugins.php /usr/share/php/smarty/internals/core.load_resource_plugin.php /usr/share/php/smarty/internals/core.process_cached_inserts.php /usr/share/php/smarty/internals/core.process_compiled_include.php /usr/share/php/smarty/internals/core.read_cache_file.php /usr/share/php/smarty/internals/core.rm_auto.php /usr/share/php/smarty/internals/core.rmdir.php /usr/share/php/smarty/internals/core.run_insert_handler.php /usr/share/php/smarty/internals/core.smarty_include_php.php /usr/share/php/smarty/internals/core.write_cache_file.php /usr/share/php/smarty/internals/core.write_compiled_include.php /usr/share/php/smarty/internals/core.write_compiled_resource.php /usr/share/php/smarty/internals/core.write_file.php /usr/share/php/smarty/plugins /usr/share/php/smarty/plugins/block.textformat.php /usr/share/php/smarty/plugins/compiler.assign.php /usr/share/php/smarty/plugins/function.assign_debug_info.php /usr/share/php/smarty/plugins/function.config_load.php /usr/share/php/smarty/plugins/function.counter.php /usr/share/php/smarty/plugins/function.cycle.php /usr/share/php/smarty/plugins/function.debug.php /usr/share/php/smarty/plugins/function.eval.php /usr/share/php/smarty/plugins/function.fetch.php /usr/share/php/smarty/plugins/function.html_checkboxes.php /usr/share/php/smarty/plugins/function.html_image.php /usr/share/php/smarty/plugins/function.html_options.php /usr/share/php/smarty/plugins/function.html_radios.php /usr/share/php/smarty/plugins/function.html_select_date.php /usr/share/php/smarty/plugins/function.html_select_time.php /usr/share/php/smarty/plugins/function.html_table.php /usr/share/php/smarty/plugins/function.mailto.php /usr/share/php/smarty/plugins/function.math.php /usr/share/php/smarty/plugins/function.popup.php /usr/share/php/smarty/plugins/function.popup_init.php /usr/share/php/smarty/plugins/modifier.capitalize.php /usr/share/php/smarty/plugins/modifier.cat.php /usr/share/php/smarty/plugins/modifier.count_characters.php /usr/share/php/smarty/plugins/modifier.count_paragraphs.php /usr/share/php/smarty/plugins/modifier.count_sentences.php /usr/share/php/smarty/plugins/modifier.count_words.php /usr/share/php/smarty/plugins/modifier.date_format.php /usr/share/php/smarty/plugins/modifier.debug_print_var.php /usr/share/php/smarty/plugins/modifier.default.php /usr/share/php/smarty/plugins/modifier.escape.php /usr/share/php/smarty/plugins/modifier.indent.php /usr/share/php/smarty/plugins/modifier.lower.php /usr/share/php/smarty/plugins/modifier.nl2br.php /usr/share/php/smarty/plugins/modifier.regex_replace.php /usr/share/php/smarty/plugins/modifier.replace.php /usr/share/php/smarty/plugins/modifier.spacify.php /usr/share/php/smarty/plugins/modifier.string_format.php /usr/share/php/smarty/plugins/modifier.strip.php /usr/share/php/smarty/plugins/modifier.strip_tags.php /usr/share/php/smarty/plugins/modifier.truncate.php /usr/share/php/smarty/plugins/modifier.upper.php /usr/share/php/smarty/plugins/modifier.wordwrap.php /usr/share/php/smarty/plugins/outputfilter.trimwhitespace.php /usr/share/php/smarty/plugins/shared.escape_special_chars.php /usr/share/php/smarty/plugins/shared.make_timestamp.php /usr/share/php/smarty/Config_File.class.php /usr/share/php/smarty/Smarty.class.php /usr/share/php/smarty/Smarty_Compiler.class.php /usr/share/php/smarty/debug.tpl /usr/share/doc /usr/share/doc/smarty /usr/share/doc/smarty/BUGS /usr/share/doc/smarty/FAQ.gz /usr/share/doc/smarty/NEWS.gz /usr/share/doc/smarty/README /usr/share/doc/smarty/NEWS.Debian.gz /usr/share/doc/smarty/TODO /usr/share/doc/smarty/QUICK_START /usr/share/doc/smarty/demo /usr/share/doc/smarty/demo/index.php /usr/share/doc/smarty/demo/templates /usr/share/doc/smarty/demo/templates/footer.tpl /usr/share/doc/smarty/demo/templates/header.tpl /usr/share/doc/smarty/demo/templates/index.tpl /usr/share/doc/smarty/demo/templates_c /usr/share/doc/smarty/demo/configs /usr/share/doc/smarty/demo/configs/test.conf /usr/share/doc/smarty/smarty_icon.README /usr/share/doc/smarty/unit_test /usr/share/doc/smarty/unit_test/config.php /usr/share/doc/smarty/unit_test/templates /usr/share/doc/smarty/unit_test/templates/assign_var.tpl /usr/share/doc/smarty/unit_test/templates/constant.tpl /usr/share/doc/smarty/unit_test/templates/parse_math.tpl /usr/share/doc/smarty/unit_test/templates/parse_obj_meth.tpl /usr/share/doc/smarty/unit_test/templates/index.tpl /usr/share/doc/smarty/unit_test/templates_c /usr/share/doc/smarty/unit_test/cache /usr/share/doc/smarty/unit_test/smarty_unit_test.php /usr/share/doc/smarty/unit_test/README /usr/share/doc/smarty/unit_test/smarty_unit_test_gui.php /usr/share/doc/smarty/unit_test/configs /usr/share/doc/smarty/unit_test/configs/globals_double_quotes.conf /usr/share/doc/smarty/unit_test/configs/globals_single_quotes.conf /usr/share/doc/smarty/unit_test/test_cases.php.gz /usr/share/doc/smarty/changelog.gz /usr/share/doc/smarty/README.Debian /usr/share/doc/smarty/copyright /usr/share/doc/smarty/ChangeLog.gz /usr/share/doc/smarty/RELEASE_NOTES.gz /usr/share/doc/smarty/changelog.Debian.gz /usr/share/lintian /usr/share/lintian/overrides /usr/share/lintian/overrides/smarty
La carpeta /usr/share/php és la carpeta on es troben les llibreries adicionals de PHP. A la configuració de PHP:
/etc/php5/apache2/php.ini
Aquesta carpeta forma part de l'include path.
Primer cal tenir instal·lat smarty al sistema, ja sigui com una llibreria encastada a la nostra aplicació o com una llibreria compartida de PHP al nostre servidors web. Consulteu els apartats anteriors referents a la instal·lació d'smarty.
Tota aplicació que faci ús d'smarty ha de tenir
$ cd path/a/la/vostra_aplicació $ mkdir smarty $ mkdir smarty/templates; mkdir smarty/templates_c; mkdir smarty/cache; mkdir smarty/configs
Cal donar les permisos correctes a les carpetes. Bàsicament el que es fa és fer que algunes de les carpetes sigui propietat de l'usuari que executa el servidor web (suposem que és tracta de l'usuari www-data - usuari típic en distribucions Linux de la família Debian amb servidors Apache -):
$ sudo chown www-data:www-data smarty/templates_c; sudo chown www-data:www-data smarty/cache; sudo chmod 775 smarty/templates_c; sudo chmod 775 smarty/cache
NOTA: A la web d'smarty proposen l'usuari nobody! Cal però utilitzar un usuari que tingui permissos per modificar fitxers des del servidor web. A Debian/Ubuntu és l'usuari www-data
Si utilitzeu subversion voldreu ignorar (que no es guardin al repositori) les carpetes cache i templates_c. Consulteu:
$ svn propset svn:ignore '*' cache/ $ svn propset svn:ignore '*' templates_c/ Subversion#Excloure_un_directori
Instal·leu smarty:
$ sudo apt-get install smarty
Un script PHP que vulgui utilitzar smarty tindrà un codi similar a
<?php // put full path to Smarty.class.php require('/usr/share/php/smarty/Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = '/web/www.domain.com/smarty/templates'; $smarty->compile_dir = '/web/www.domain.com/smarty/templates_c'; $smarty->cache_dir = '/web/www.domain.com/smarty/cache'; $smarty->config_dir = '/web/www.domain.com/smarty/configs'; $smarty->assign('name', 'Ned'); $smarty->display('index.tpl'); ?>
Anem a fer un exemple bàsic. Suposem que ja teniu instal·lat un sistema LAMP, si no és així executeu:
$ sudo tasksel lamp-server
També instal·leu smarty si encara no l'havíeu instal.lat:
$ sudo apt-get install smarty
Aneu a la carpeta /var/www:
$ cd /var/www
creeu una carpeta:
$ sudo mkdir exemple_smarty $ cd exemple_smarty
Prepareu smarty segons les instruccions de l'apartat anterior:
$ sudo mkdir smarty $ sudo mkdir smarty/templates $ sudo mkdir smarty/templates_c $ sudo mkdir smarty/cache $ sudo mkdir smarty/configs
Cal donar les permisos correctes a les carpetes. Bàsicament el que es fa és fer que algunes de les carpetes sigui propietat de l'usuari que executa el servidor web (suposem que és tracta de l'usuari www-data - usuari típic en distribucions Linux de la família Debian amb servidors Apache -):
$ sudo chown www-data:www-data smarty/templates_c $ sudo chown www-data:www-data smarty/cache $ sudo chmod 775 smarty/templates_c $ sudo chmod 775 smarty/cache
I creeu el següent fitxer index.php:
$ sudo joe index.php
I poseu:
<?php // put full path to Smarty.class.php require('/usr/share/php/smarty/Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = 'smarty/templates'; $smarty->compile_dir = 'smarty/templates_c'; $smarty->cache_dir = 'smarty/cache'; $smarty->config_dir = 'smarty/configs'; $smarty->assign('name', 'Sergi Tur Badenas'); $smarty->display('index.tpl'); ?>
NOTA: Canvieu el valor de la variable name pel vostre nom!
Ara cal que creeu el fitxer plantilla:
$ sudo joe /var/www/exemple_smarty/templates/index.tpl
I poseu:
<html> <head> <title>Smarty</title> </head> <body> Hello, {$name}! </body> </html>
Proveu l'exemple accedint a:
http://localhost/exemple_smarty
Aviat us adonareu que utilitzar en cada fitxer de la vostra aplicació el codi:
// put full path to Smarty.class.php require('/usr/share/php/smarty/Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = 'smarty/templates'; $smarty->compile_dir = 'smarty/templates_c'; $smarty->cache_dir = 'smarty/cache'; $smarty->config_dir = 'smarty/configs';
és com a mínim redundant i repetitiu. Per aquest raó la majoria d'aplicacions utilitzant un include que és el que realment s'encarrega de configurar smarty.
Per exemple webfaltes, el fitxer include és includes/smarty.php:
<?php //Plantilles Smarty require(_SMARTY_LIB.'Smarty.class.php'); $smarty = new Smarty; $smarty->template_dir = _SMARTY_TEMPLATES_FOLDER; $smarty->compile_dir = _SMARTY_TEMPLATES_C_FOLDER; $smarty->cache_dir = _SMARTY_CACHE_FOLDER; $smarty->config_dir = _SMARTY_CONFIGS_FOLDER; #require(_SMARTY_GETTEXT_LIB.'smarty-gettext.php'); #$smarty->register_block('t', 'smarty-translate'); ?>
Cada fitxer que vol utilitzar smarty té el codi:
//Smarty require_once _INCLUDES."smarty.php";
<body> {* this multiline comment is not sent to browser *} {* include the header file here *} {include file="header.tpl"} {* Dev note: $includeFile is assigned foo.php script *} <!-- this html comment is sent to browser --> {include file=$includeFile} {include file=#includeFile#} {* display dropdown lists *} <select name="company"> {html_options options=$vals selected=$selected_id} </select> </body>
{$foo} <-- displaying a simple variable (non array/object) {$foo[4]} <-- display the 5th element of a zero-indexed array {$foo.bar} <-- display the "bar" key value of an array, similar to PHP $foo['bar'] {$foo.$bar} <-- display variable key value of an array, similar to PHP $foo[$bar] {$foo->bar} <-- display the object property "bar" {$foo->bar()} <-- display the return value of object method "bar" {#foo#} <-- display the config file variable "foo" {$smarty.config.foo} <-- synonym for {#foo#} {$foo[bar]} <-- syntax only valid in a section loop, see {section} {assign var=foo value="baa"}{$foo} <-- displays "baa", see {assign} Many other combinations are allowed {$foo.bar.baz} {$foo.$bar.$baz} {$foo[4].baz} {$foo[4].$baz} {$foo.bar.baz[4]} {$foo->bar($baz,2,$bar)} <-- passing parameters {"foo"} <-- static values are allowed
Exemples:
{config_load file="colors.conf"} {include file="header.tpl"} {if $highlight_name} Welcome, <font color="{#fontColor#}">{$name}!</font> {else} Welcome, {$name}! {/if} {include file="footer.tpl"}
Les funcions integrades de sèrie són:
capture config_load {foreach},{foreachelse} include {include_php} insert if,elseif,else {ldelim},{rdelim} literal {php} section,sectionelse {strip}
Consulteu-les a:
Atributs:
{include file="header.tpl"} {include file="header.tpl" attrib_name="attrib value"} {include file=$includeFile} {include file=#includeFile# title="Smarty is cool"} {html_select_date display_days=yes} <select name="company"> {html_options options=$choices selected=$selected} </select>
Cal posar-lo entre literals:
{literal} <script type="text/javascript"> var bas_cal,dp_cal,ms_cal; window.onload = function () { dp_cal = new Epoch('epoch_popup','popup',document.getElementById('data_neixement')); }; {/literal}
</script>
S'instal·len a la carpeta /usr/share/php/smarty/libs/plugins
Consulteu Smarty-gettext.
El manual en castellà el trobareu a:
http://www.smarty.net/manual/es/
Solución: Borrar las carpetas donde están compiladas las plantillas y las de caché
En el caso del gosa:
/var/spool/gosa
Si al utilitzar una aplicació web PHP amb Smarty us dona el següent error:
Fatal error: Smarty error: the $compile_dir '/home/sergi/workspaces/php/webfaltes_sourceforge/smarty/templates_c' does not exist, or is not a directory. in /home/sergi /workspaces/php/webfaltes_sourceforge/libs/smarty/libs/Smarty.class.php on line 1113
Heu de seguir els passos de la instal·lació i cal crear entre d'altres la carpeta templates_c. Consulteu:
Smarty#Preparant_una_aplicaci.C3.B3_per_tal_d.27utilitzar_Smarty
vegeu la solució