From b32c582f45317aa880b7be1552356e5760b706a1 Mon Sep 17 00:00:00 2001 From: andrey Date: Thu, 28 Feb 2002 22:41:41 +0000 Subject: [PATCH] *** empty log message *** --- TESTIMONIALS | 9 + docs/appendixes.sgml | 20 +- docs/designers.sgml | 349 ++++++++--------- docs/programmers.sgml | 887 +++++++++++++++++++++--------------------- 4 files changed, 620 insertions(+), 645 deletions(-) create mode 100644 TESTIMONIALS diff --git a/TESTIMONIALS b/TESTIMONIALS new file mode 100644 index 00000000..7abf6454 --- /dev/null +++ b/TESTIMONIALS @@ -0,0 +1,9 @@ +"I just got my first paying contract for a local small business and in my + program I'm using Smarty. Smarty is an absolute joy to work with - + at first, I didn't like the idea of populating variables/arrays and then + assigning those directly (since I'd been using FastTemplates for so long), + but after using this system for a while, I don't think I can ever go back + (I even switched my Perl template engine to HTML-Template-2.4 which + operates on the same concepts). Anyway, thanks for saving me time and + headache!" + -- Brian E. Lozier diff --git a/docs/appendixes.sgml b/docs/appendixes.sgml index 5dbd25c7..d63384b4 100644 --- a/docs/appendixes.sgml +++ b/docs/appendixes.sgml @@ -3,7 +3,7 @@ Troubleshooting - + Smarty/PHP errors Smarty can catch many errors such as missing tag attributes @@ -55,7 +55,7 @@ Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75 Tips & Tricks - + Blank Variable Handling There may be times when you want to print a default value for an empty @@ -82,7 +82,8 @@ Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75 {$title|default:"&nbsp;"} - + + Default Variable Handling If a variable is used frequently throughout your templates, applying @@ -100,7 +101,7 @@ Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75 {$title} - + Passing variable title to header template When the majority of your templates use the same headers and footers, it @@ -154,7 +155,7 @@ footer.tpl default variable modifier. - + Dates As a rule of thumb, always pass dates to Smarty as timestamps. @@ -213,7 +214,7 @@ function makeTimeStamp($year="",$month="",$day="") } - + WAP/WML WAP/WML templates require a php Content-Type header to be passed along @@ -353,7 +354,7 @@ index.tpl Stock Name: {$ticker_name} Stock Price: {$ticker_price} - + Obfuscating E-mail Addresses Do you ever wonder how your E-mail address gets on so many spam mailing @@ -388,9 +389,8 @@ href="mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&a Technical Note - This method isn't 100% foolproof. Although highly unlikely, - a spammer could conceivably write his e-mail collecter to decode these - values. + This method isn't 100% foolproof. Although highly unlikely, a spammer + could conceivably write his e-mail collector to decode these values. diff --git a/docs/designers.sgml b/docs/designers.sgml index 2b128570..44d181a9 100644 --- a/docs/designers.sgml +++ b/docs/designers.sgml @@ -1,4 +1,4 @@ - + Smarty For Template Designers Template Language @@ -141,7 +141,7 @@ <body bgcolr="{#bgcolor#}"> - + Variables assigned from PHP Variables that are assigned from PHP are referenced by preceding @@ -162,7 +162,7 @@ Hello Doug, glad to see you could make it. Your last login was on January 11th, 2001. - + Associative arrays You can also reference associative array variables that are @@ -170,7 +170,7 @@ Your last login was on January 11th, 2001. symbol. -displaying assigned associative array variables +accessing associative array variables {$Contacts.fax}<br> {$Contacts.email}<br> @@ -187,14 +187,14 @@ zaphod@slartibartfast.com<br> - + Array indexes You can reference arrays by their index, much like native PHP syntax. -displaying arrays by index +accessing arrays by index {$Contacts[0]}<br> {$Contacts[1]}<br> @@ -203,14 +203,14 @@ zaphod@slartibartfast.com<br> {$Contacts[0][1]}<br> - + Objects Properties of objects assigned from PHP can be referenced by specifying the property name after the '->' symbol. -displaying object properties +accessing object properties name: {$person->name}<br> email: {$person->email}<br> @@ -221,19 +221,17 @@ name: Zaphod Beeblebrox<br> email: zaphod@slartibartfast.com<br> - + - + Variables loaded from config files - Variables that are passed in from config files are displayed by enclosing - them with hash marks (#) and enclosing the variable in delimiters - like so: {#varname#} + Variables that are loaded from the config files are referenced by enclosing + them within hash marks (#). - -displaying config variables +config variables <html> <title>{#pageTitle#}</title> @@ -249,43 +247,31 @@ email: zaphod@slartibartfast.com<br> </html> - Config file variables cannot be displayed until + Config file variables cannot be used until after they are loaded in from a config file. This procedure is explained later in this document under - config_load. + config_load. - - Variables internal to template - - Variables that are internal to the templates are displayed by using - the special variable {$smarty}. For instance, you can reference the - current date/time with {$smarty.now}, or section loops have - properties that are internal variables. - - - - {$smarty} reserved variable - - The reserved {$smarty} variable can be used to access several - special template variables. The full list of them follows. - - - The special variable {$smarty} was added to Smarty 1.4.4. - - - Request variables - - The request variables such as get, post, cookies, server, - environment, and session variables can be accessed as demonstrated - in the examples below: - - + + {$smarty} reserved variable + + The reserved {$smarty} variable can be used to access several + special template variables. The full list of them follows. + -displaying request variables - + + Request variables + + The request variables such as get, post, cookies, server, + environment, and session variables can be accessed as demonstrated + in the examples below: + + + + displaying request variables + {* display the variable "page" given in the URL, or from a form using the GET method *} {$smarty.get.page} @@ -309,7 +295,7 @@ email: zaphod@slartibartfast.com<br> - + Current timestamp The current timestamp can be accessed with {$smarty.now}. The @@ -326,7 +312,7 @@ email: zaphod@slartibartfast.com<br> - + Output capture buffer The output captured via {capture}..{/capture} construct can be @@ -335,7 +321,7 @@ email: zaphod@slartibartfast.com<br> - + Loop properties {$smarty} variable can be used to refer to 'section' and @@ -344,43 +330,46 @@ email: zaphod@slartibartfast.com<br> foreach. - - - - Variable Modifiers - - Variable modifiers are a bit different than custom functions. Variable modifiers - alter variable contents before they are displayed to the template. All - modifiers will get the value of the variable as the first argument, and - must return a single value. Modifier parameters are separated by - colons. Any additional parameters passed to a modifier are passed as-is - positionally, much like calling a PHP function. You can also use native - PHP functions as modifiers, but only if they expect the correct - arguments. If they do not, you can always write a wrapper function in - Smarty to get what you want. You can chain as many modifiers together - on a variable as you like, separating each with a vertical pipe "|". - - - NOTE: if you apply a modifier to an array instead of a single value - variable, the modifier will be applied to every value in that array. If - you really want the entire array passed to the modifier, you must - prepend it with an "@" sign like so: {$articleTitle|@count} (this will - print out the number of elements in the $articleTitle array.) - - - Built-in Modifiers - - capitalize - - This is used to capitalize the first letter of all words in a variable. - - -capitalize - + + Variable Modifiers + + Variable modifiers can be applied to any variable to alter its contents. To + apply a modifier, specify the variable followed by the | + (pipe) and the modifier name. A modifier may accept additional parameters + that affect its behavior. These parameters follow the modifer name and are + separated by : (colon). + + + modifier example + +{* Uppercase the title *} +<h2>{$title|upper}</h2> + +{* Truncate the topic to 40 characters use ... at the end *} +Topic: {$topic|truncate:40:"..."} + + + If you apply a modifier to an array variable instead of a single value variable, + the modifier will be applied to every value in that array. If you really want + the modifier to work on an entire array as a value, you must prepend the + modifier name with an @ symbol like so: + {$articleTitle|@count} (this will print out the number of + elements in the $articleTitle array.) + + + + Built-in Modifiers + + capitalize + + This is used to capitalize the first letter of all words in a variable. + + + capitalize + {$articleTitle} {$articleTitle|capitalize} @@ -1196,19 +1185,20 @@ from dad she hasn't seen in years. Blind woman gets new kidney fr om dad she hasn't seen in years. - - - - Combining Modifiers - - You can combine as many modifiers as you like on a single variable. - This allows the ability to combine the application of different - modifiers to a single variable. The modifiers will be applied to - the variable in the order they are combined, from left to right. - - -combining modifiers - + + + + + Combining Modifiers + + You can apply as many modifiers as you like to a variable. The modifiers + will be applied to the variable in the order they are combined, from left + to right. The modifier have to be separated with a | + (pipe) symbol. + + + combining modifiers + {$articleTitle} {$articleTitle|upper|spacify} {$articleTitle|lower|spacify|truncate} @@ -1223,9 +1213,9 @@ S M O K E R S A R E P R O D U C T I V E , B U T D E A T H C U T S E s m o k e r s a r e p r o d u c t i v e , b u t d e a t h c u t s... s m o k e r s a r e p r o d u c t i v e , b u t . . . s m o k e r s a r e p. . . - + - + Built-in Functions @@ -1344,9 +1334,9 @@ s m o k e r s a r e p. . . This function is used for loading in variables from a - configuration file into the template. You must have the Config_file.class.php - file somewhere in your PHP include path for config_load to work properly. - See Config Files for more info. + configuration file into the template. + See Config Files for more + info. function config_load @@ -2570,14 +2560,14 @@ OUTPUT: - + Custom Functions Smarty comes with several additional functions that you can use in the templates. - + Additional Functions assign @@ -4086,24 +4076,21 @@ OUTPUT: - + - Config Files - - Config files are handy for designers to manage global template - variables from one file. One example is template colors. Normally if - you wanted to change the color scheme of an application, you would have - to go through each and every template file and change the colors. With - a config file, the colors can be kept in one place, and only one file - needs to be updated. Note that to use config files, you must place the - Config_File.class.php in your PHP include path. Config_File.class.php - comes bundled with Smarty. Smarty will implicitly include the file if - you don't already include it in your application. - - -Example of config file syntax - + Config Files + + Config files are handy for designers to manage global template + variables from one file. One example is template colors. Normally if + you wanted to change the color scheme of an application, you would have + to go through each and every template file and change the colors. With + a config file, the colors can be kept in one place, and only one file + needs to be updated. + + + Example of config file syntax + # global variables pageTitle = "Main Menu" bodyBgColor = #000000 @@ -4125,75 +4112,73 @@ Intro = """This is a value that spans more host=my.domain.com db=ADDRESSBOOK user=php-user -pass=foobar - - - - Values of config file variables can be in quotes, but not necessary. - You can use either single or double quotes. If you have a value that - spans more than one line, enclose the entire value with triple quotes - ("""). You can put comments into config files by any syntax that is - not a valid config file syntax. We recommend using a hashmark (#) at the - beginning of the line. - - - This config file example has two sections. Section names are enclosed - in brackets []. The four variables at the top are global - variables, or variables not within a section. These variables are - always loaded from the config file. - If a particular section is loaded, then the global variables and the - variables from that section are loaded. If a variable exists both as - a global and in a section, the section variable is used. If you name two - variables the same within a section, the last one will be used. - - - Config files are loaded into templates with the built-in function - called config_load. - - - You can hide variables or entire sections by prepending the variable - name or section name with a period. This is useful if your - application reads the config files and gets sensitive data from them - that the template engine does not need. If you have third parties - doing template editing, you can be certain that they cannot read - sensitive data from the config file by loading it into the template. - This is new in Smarty 1.4.6. - - - +pass=foobar + + + Values of config file variables can be in quotes, but not necessary. + You can use either single or double quotes. If you have a value that + spans more than one line, enclose the entire value with triple quotes + ("""). You can put comments into config files by any syntax that is not + a valid config file syntax. We recommend using a # + (hash) at the beginning of the line. + + + This config file example has two sections. Section names are enclosed in + brackets []. Section names can be arbitrary strings not containing + [ or ] symbols. The four variables + at the top are global variables, or variables not within a section. + These variables are always loaded from the config file. If a particular + section is loaded, then the global variables and the variables from that + section are also loaded. If a variable exists both as a global and in a + section, the section variable is used. If you name two variables the + same within a section, the last one will be used. + + + Config files are loaded into templates with the built-in function + config_load. + + + You can hide variables or entire sections by prepending the variable + name or section name with a period. This is useful if your application + reads the config files and gets sensitive data from them that the + template engine does not need. If you have third parties doing template + editing, you can be certain that they cannot read sensitive data from + the config file by loading it into the template. + + Debugging Console - There is a dubugging console included with Smarty. The console informs you - of all the included templates, assigned variables and config file variables - for the current invocation of the template. A template named "debug.tpl" is - included with the distribution of Smarty which controls the formatting of - the console. Set $debugging to true in Smarty, and if needed set $debug_tpl - to the template resource path for debug.tpl (this is in $template_dir by - default.) When you load the page, a javascript console window should pop up - and give you the names of all the included templates and assigned variables - for the current page. To disable the debugging console, set $debugging to - false. You can also temporarily turn on the debugging console by putting - SMARTY_DEBUG in the URL if you enable this option with $debugging_ctrl. + There is a debugging console included with Smarty. The console informs you + of all the included templates, assigned variables and config file variables + for the current invocation of the template. A template named "debug.tpl" is + included with the distribution of Smarty which controls the formatting of + the console. Set $debugging to true in Smarty, and if needed set $debug_tpl + to the template resource path for debug.tpl (this is in $template_dir by + default.) When you load the page, a javascript console window should pop up + and give you the names of all the included templates and assigned variables + for the current page. To disable the debugging console, set $debugging to + false. You can also temporarily turn on the debugging console by putting + SMARTY_DEBUG in the URL if you enable this option with $debugging_ctrl. - Technical Note - - The debugging console does not work when you use the fetch() - API, only when using display(). It is a set of javascript statements added - to the very bottom of the generated template. If you do not like javascript, - you can edit the debug.tpl template to format the output however you like. - Debug data is not cached and debug.tpl info is not included in the output of - the debug console. - + Technical Note + + The debugging console does not work when you use the fetch() + API, only when using display(). It is a set of javascript statements added + to the very bottom of the generated template. If you do not like javascript, + you can edit the debug.tpl template to format the output however you like. + Debug data is not cached and debug.tpl info is not included in the output of + the debug console. + - - The load times of each template and config file are in seconds, or - fractions thereof. - - - + + The load times of each template and config file are in seconds, or + fractions thereof. + + + diff --git a/docs/programmers.sgml b/docs/programmers.sgml index ee119a65..c67eb3f8 100644 --- a/docs/programmers.sgml +++ b/docs/programmers.sgml @@ -1,4 +1,4 @@ - + Smarty For Programmers Smarty API @@ -139,7 +139,7 @@ $global_assign to a default value. - + $compile_check Upon each invocation of the PHP application, Smarty tests to @@ -271,7 +271,7 @@ NOTE: Embedding PHP code into templates is highly discouraged. Use custom functions or - modifiers instead. + modifiers instead. @@ -994,51 +994,439 @@ echo $output; - - Extending Smarty With Plugins - - Version 2.0 introduced the plugin architecture that is used - for almost all the customizable functionality of Smarty. This includes: - - functions - modifiers - compiler functions - prefilters - postfilters - resources - inserts - - With the exception of resources, backwards compatibility with the old - way of registering handler functions via register_* API is preserved. If - you did not use the API but instead modified the class variables - $custom_funcs, $custom_mods, and - other ones directly, then you will need to adjust your scripts to either - use the API or convert your custom functionality into plugins. - - - - How Plugins Work + + Advanced Features + + Prefilters - Plugins are always loaded on demand. Only the specific modifiers, - functions, resources, etc invoked in the templates or PHP scripts will - be loaded. Moreover, each plugin is loaded only once, even if you have - several different instances of Smarty running within the same request. - - - Pre/post-filters are a bit of a special case. If a pre/post-filter - plugin is found in the plugins directory, it will always be loaded - because these filters are never explicitly mentioned in the template - language. This also means that the order in which multiple prefilters - or postfilters is executed depends on the way they are named - (basically, alphabetical order). - - - There is only one plugins directory (for performance reasons). To - install a plugin, simply place it in the directory and Smarty will use - it automatically. + Template prefilters are PHP functions that your templates are ran through + before they are compiled. This is good for preprocessing your templates + to remove unwanted comments, keeping an eye on what people are putting + in their templates, etc. Prefilters are processed in the order they are + registered or loaded from + the plugin directory. + Smarty will pass the template source code as the first argument, an + expect the function to return the resulting template source code. + + using a template prefilter + +<?php +// put this in your application +function remove_dw_comments($tpl_source) +{ + return preg_replace("/<!--#.*-->/U","",$tpl_source); +} + +// register the prefilter +$smarty->register_prefilter("remove_dw_comments"); +$smarty->display("index.tpl"); +?> + +{* Smarty template index.tpl *} +<!--# this line will get removed by the prefilter --> + + + Postfilters + + Template postfilters are PHP functions that your templates are ran through + after they are compiled. Postfilters are processed in the order they are + registered or loaded + from the plugin + directory. Smarty will pass the compiled template code as the first + argument, an expect the function to return the result of the + processing. + + + using a template postfilter + +<?php +// put this in your application +function add_header_comment($tpl_source) +{ + return "<?php echo \"<!-- Created by Smarty! -->\n\" ?>\n".$tpl_source; +} + +// register the postfilter +$smarty->register_postfilter("add_header_comment"); +$smarty->display("index.tpl"); +?> + +{* compiled Smarty template index.tpl *} +<!-- Created by Smarty! --> +{* rest of template content... *} + + + + + + Cache Handler Function + + As an alternative to using the default file-based caching mechanism, you + can specify a custom cache handling function that will be used to read, + write and clear cached files. + + + Create a function in your application that Smarty will use as a + cache handler. Set the name of it in the + $cache_handler_func + class variable. Smarty will now use this to handle cached data. The + first argument is the action, which will be one of 'read', 'write' and + 'clear'. The second parameter is the Smarty object. The third parameter + is the cached content. Upon a write, Smarty passes the cached content + in these parameters. Upon a 'read', Smarty expects your function to + accept this parameter by reference and populate it with the cached + data. Upon a 'clear', pass a dummy variable here since it is not used. + The fourth parameter is the name of the template file (needed for + read/write), the fifth parameter is the cache_id (optional), and the + sixth is the compile_id (optional). + + + example using MySQL as a cache source + +<?php +/* + +example usage: + +include('Smarty.class.php'); +include('mysql_cache_handler.php'); + +$smarty = new Smarty; +$smarty->cache_handler_func = 'mysql_cache_handler'; + +$smarty->display('index.tpl'); + + +mysql database is expected in this format: + +create database SMARTY_CACHE; + +create table CACHE_PAGES( +CacheID char(32) PRIMARY KEY, +CacheContents MEDIUMTEXT NOT NULL +); + +*/ + +function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null) +{ + // set db host, user and pass here + $db_host = 'localhost'; + $db_user = 'myuser'; + $db_pass = 'mypass'; + $db_name = 'SMARTY_CACHE'; + $use_gzip = false; + + // create unique cache id + $CacheID = md5($tpl_file.$cache_id.$compile_id); + + if(! $link = mysql_pconnect($db_host, $db_user, $db_pass)) { + $smarty_obj->_trigger_error_msg("cache_handler: could not connect to database"); + return false; + } + mysql_select_db($db_name); + + switch ($action) { + case 'read': + // save cache to database + $results = mysql_query("select CacheContents from CACHE_PAGES where CacheID='$CacheID'"); + if(!$results) { + $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + } + $row = mysql_fetch_array($results,MYSQL_ASSOC); + + if($use_gzip && function_exists("gzuncompress")) { + $cache_contents = gzuncompress($row["CacheContents"]); + } else { + $cache_contents = $row["CacheContents"]; + } + $return = $results; + break; + case 'write': + // save cache to database + + if($use_gzip && function_exists("gzcompress")) { + // compress the contents for storage efficiency + $contents = gzcompress($cache_content); + } else { + $contents = $cache_content; + } + $results = mysql_query("replace into CACHE_PAGES values( + '$CacheID', + '".addslashes($contents)."') + "); + if(!$results) { + $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + } + $return = $results; + break; + case 'clear': + // clear cache info + if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) { + // clear them all + $results = mysql_query("delete from CACHE_PAGES"); + } else { + $results = mysql_query("delete from CACHE_PAGES where CacheID='$CacheID'"); + } + if(!$results) { + $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + } + $return = $results; + break; + default: + // error, unknown action + $smarty_obj->_trigger_error_msg("cache_handler: unknown action \"$action\""); + $return = false; + break; + } + mysql_close($link); + return $return; + +} + +?> + + + + + Resources + + The templates may come from a variety of sources. When you display or + fetch a template, or when you include a template from within another + template, you supply a resource type, followed by the appropriate path + and template name. + + + Templates from $template_dir + + Templates from the $template_dir do not require a template + resource, although you can use the file: resource for consistancy. + Just supply the path to the template you want to use relative to + the $template_dir root directory. + + + using templates from $template_dir + +// from PHP script +$smarty->display("index.tpl"); +$smarty->display("admin/menu.tpl"); +$smarty->display("file:admin/menu.tpl"); // same as one above + +{* from within Smarty template *} +{include file="index.tpl"} +{include file="file:index.tpl"} {* same as one above *} + + + + Templates from any directory + + Templates outside of the $template_dir require the file: template + resource type, followed by the absolute path and name of the + template. + + + using templates from any directory + +// from PHP script +$smarty->display("file:/export/templates/index.tpl"); +$smarty->display("file:/path/to/my/templates/menu.tpl"); + +{* from within Smarty template *} +{include file="file:/usr/local/share/templates/navigation.tpl"} + + + + Windows Filepaths + + If you are using a Windows machine, filepaths usually include a + drive letter (C:) at the beginning of the pathname. Be sure to use + "file:" in the path to avoid namespace conflicts and get the + desired results. + + + using templates from windows file paths + +// from PHP script +$smarty->display("file:C:/export/templates/index.tpl"); +$smarty->display("file:F:/path/to/my/templates/menu.tpl"); + +{* from within Smarty template *} +{include file="file:D:/usr/local/share/templates/navigation.tpl"} + + + + + + Templates from other sources + + You can retrieve templates using whatever possible source you can + access with PHP: databases, sockets, LDAP, and so on. You do this + by writing resource plugin functions and registering them with + Smarty. + + + + See resource plugins + section for more information on the functions you are supposed + to provide. + + + + + Note that you cannot override the built-in + file resource, but you can provide a resource + that fetches templates from the file system in some other way by + registering under another resource name. + + + + using custom resources + +// from PHP script + +// put these function somewhere in your application +function db_get_template ($tpl_name, &tpl_source, &$smarty_obj) +{ + // do database call here to fetch your template, + // populating $tpl_source + $sql = new SQL; + $sql->query("select tpl_source + from my_table + where tpl_name='$tpl_name'"); + if ($sql->num_rows) { + $tpl_source = $sql->record['tpl_source']; + return true; + } else { + return false; + } +} + +function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) +{ + // do database call here to populate $tpl_timestamp. + $sql = new SQL; + $sql->query("select tpl_timestamp + from my_table + where tpl_name='$tpl_name'"); + if ($sql->num_rows) { + $tpl_timestamp = $sql->record['tpl_timestamp']; + return true; + } else { + return false; + } +} + +function db_get_secure($tpl_name, &$smarty_obj) +{ + // assume all templates are secure + return true; +} + +function db_get_trusted($tpl_name, &$smarty_obj) +{ + // not used for templates +} + +// register the resource name "db" +$smarty->register_resource("db", array("db_get_template", + "db_get_timestamp", + "db_get_secure", + "db_get_trusted")); + +// using resource from php script +$smarty->display("db:index.tpl"); + +{* using resource from within Smarty template *} +{include file="db:/extras/navigation.tpl"} + + + + + Default template handler function + + You can specify a function that is used to retrieve template + contents in the event the template cannot be retrieved from its + resource. One use of this is to create templates that do not exist + on-the-fly. + + + using the default template handler function + +<?php +// put this function somewhere in your application + +function make_template ($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj) +{ + if( $resource_type == 'file' ) { + if ( ! is_readable ( $resource_name )) { + // create the template file, return contents. + $template_source = "This is a new template."; + $template_timestamp = time(); + $smarty_obj->_write_file($resource_name,$template_source); + return true; + } + } else { + // not a file + return false; + } +} + +// set the default handler +$smarty->default_template_handler_func = 'make_template'; +?> + + + + + + + Extending Smarty With Plugins + + Version 2.0 introduced the plugin architecture that is used + for almost all the customizable functionality of Smarty. This includes: + + functions + modifiers + compiler functions + prefilters + postfilters + resources + inserts + + With the exception of resources, backwards compatibility with the old + way of registering handler functions via register_* API is preserved. If + you did not use the API but instead modified the class variables + $custom_funcs, $custom_mods, and + other ones directly, then you will need to adjust your scripts to either + use the API or convert your custom functionality into plugins. + + + + How Plugins Work + + Plugins are always loaded on demand. Only the specific modifiers, + functions, resources, etc invoked in the templates or PHP scripts will + be loaded. Moreover, each plugin is loaded only once, even if you have + several different instances of Smarty running within the same request. + + + Pre/post-filters are a bit of a special case. If a pre/post-filter + plugin is found in the plugins directory, it will always be loaded + because these filters are never explicitly mentioned in the template + language. This also means that the order in which multiple prefilters + or postfilters is executed depends on the way they are named + (basically, alphabetical order). + + + There is only one plugins directory (for performance reasons). To + install a plugin, simply place it in the directory and Smarty will use + it automatically. + + + Naming Conventions @@ -1376,7 +1764,8 @@ echo 'index.tpl compiled at 2002-02-20 20:02'; - Prefilters/Postfilters + + Prefilters/Postfilters Prefilter and postfilter plugins are very similar in concept; where they differ is in the execution -- more precisely the time of their @@ -1640,412 +2029,4 @@ function smarty_insert_time($params, &$smarty) - - Advanced Features - - Prefilters - - Template prefilters are PHP functions that your templates are ran through - before they are compiled. This is good for preprocessing your templates - to remove unwanted comments, keeping an eye on what people are putting - in their templates, etc. Prefilters are processed in the order they are - registered. - - - Example of a Template Prefilter - - Create a function in your application that Smarty will use as a - template prefilter. Smarty will pass the template source code as the - first argument, an expect the function to return the resulting - template source code. - - - NOTE: As of Smarty 1.4.5, the Smarty object is passed as the second - argument. This way you can reference and modify information in the - Smarty object from within the prefilter function. - - - -using a template prefilter - -// put this in your application, or in Smarty.addons.php -function remove_dw_comments($tpl_source) { - return preg_replace("/<!--#.*-->/U","",$tpl_source); -} - -// register the prefilter -$smarty->register_prefilter("remove_dw_comments"); -$smarty->display("index.tpl"); - -{* from within Smarty template *} -<!--# this line will get removed by the prefilter --> - - - - - Postfilters - - Template postfilters are PHP functions that your templates are ran through - after they are compiled. Postfilters are processed in the order they are - registered. - - - Example of a Template Postfilter - - Create a function in your application that Smarty will use as a - template postfilter. Smarty will pass the template source code as the - first argument, an expect the function to return the resulting - template source code. - - - The Smarty object is passed as the second argument. This way you - can reference and modify information in the Smarty object from - within the prefilter function. - - - -using a template postfilter - -// this program puts a -// put this in your application, or in Smarty.addons.php -function add_header_comment($tpl_source) { - return "\n\" ?>\n".$tpl_source; -} - -// register the postfilter -$smarty->register_postfilter("add_header_comment"); -$smarty->display("index.tpl"); - -{* from within Smarty template *} - -{* rest of template content... *} - - - - - Cache Handling Function - - As an alternative to using the default file-based caching mechanism, you - can specify a custom cache handling function that will be used to read, - write and clear cached files. - - - Example of a Template Cache Handling Function - - Create a function in your application that Smarty will use as a - cache handler. Set the name of it in the $cache_handler_func class - variable. Smarty will now use this to handle cached data. The first - argument is the action, which will be one of 'read', 'write' and - 'clear'. The second parameter is the smarty object. The third - parameter is the cached content. Upon a write, Smarty passes the - cached content in these parameters. Upon a 'read', Smarty expects - your function to pass this by reference and populate it with the - cached data. Upon a 'clear', pass a dummy variable here since it is - not used. The fourth parameter is the name of the template file - (needed for read/write), the fifth parameter is the cache_id - (optional), and the sixth is the compile_id (optional) - - - -example using MySQL as a cache source - -<?php - -/* - -example usage: - -include('Smarty.class.php'); -include('mysql_cache_handler.php'); - -$smarty = new Smarty; -$smarty->cache_handler_func='mysql_cache_handler'; - -$smarty->display('index.tpl'); - - -mysql database is expected in this format: - -create database SMARTY_CACHE; - -create table CACHE_PAGES( -CacheID char(32) PRIMARY KEY, -CacheContents MEDIUMTEXT NOT NULL -); - -*/ - -function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null) { - // set db host, user and pass here - $db_host = 'localhost'; - $db_user = 'myuser'; - $db_pass = 'mypass'; - $db_name = 'SMARTY_CACHE'; - $use_gzip = false; - - // create unique cache id - $CacheID = md5($tpl_file.$cache_id.$compile_id); - - if(! $link = mysql_pconnect($db_host, $db_user, $db_pass)) { - $smarty_obj->_trigger_error_msg("cache_handler: could not connect to database"); - return false; - } - mysql_select_db($db_name); - - switch ($action) { - case 'read': - // save cache to database - $results = mysql_query("select CacheContents from CACHE_PAGES where CacheID='$CacheID'"); - if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); - } - $row = mysql_fetch_array($results,MYSQL_ASSOC); - - if($use_gzip && function_exists("gzuncompress")) { - $cache_contents = gzuncompress($row["CacheContents"]); - } else { - $cache_contents = $row["CacheContents"]; - } - $return = $results; - break; - case 'write': - // save cache to database - - if($use_gzip && function_exists("gzcompress")) { - // compress the contents for storage efficiency - $contents = gzcompress($cache_content); - } else { - $contents = $cache_content; - } - $results = mysql_query("replace into CACHE_PAGES values( - '$CacheID', - '".addslashes($contents)."') - "); - if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); - } - $return = $results; - break; - case 'clear': - // clear cache info - if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) { - // clear them all - $results = mysql_query("delete from CACHE_PAGES"); - } else { - $results = mysql_query("delete from CACHE_PAGES where CacheID='$CacheID'"); - } - if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); - } - $return = $results; - break; - default: - // error, unknown action - $smarty_obj->_trigger_error_msg("cache_handler: unknown action \"$action\""); - $return = false; - break; - } - mysql_close($link); - return $return; - -} - -?> - - - - - - Resources - - Your templates may come from a variety of sources. When you display or - fetch a template, or when you include a template from within another - template, you supply a resource type, followed by the appropriate path - and template name. - - - Templates from $template_dir - - Templates from the $template_dir do not require a template - resource, although you can use the file: resource for consistancy. - Just supply the path to the template you want to use relative to - the $template_dir root directory. - - - -using templates from $template_dir - -// from PHP script -$smarty->display("index.tpl"); -$smarty->display("admin/menu.tpl"); -$smarty->display("file:admin/menu.tpl"); // same as one above - -{* from within Smarty template *} -{include file="index.tpl"} -{include file="file:index.tpl"} {* same as one above *} - - - - Templates from any directory - - Templates outside of the $template_dir require the file: template - resource type, followed by the absolute path and name of the - template. - - - - using templates from any directory - -// from PHP script -$smarty->display("file:/export/templates/index.tpl"); -$smarty->display("file:/path/to/my/templates/menu.tpl"); - -{* from within Smarty template *} -{include file="file:/usr/local/share/templates/navigation.tpl"} - - - Windows Filepaths - - If you are using a Windows machine, filepaths usually include a - drive letter (C:) at the beginning of the pathname. Be sure to use - "file:" in the path to avoid namespace conflicts and get the - desired results. - - - using templates from windows file paths - -// from PHP script -$smarty->display("file:C:/export/templates/index.tpl"); -$smarty->display("file:F:/path/to/my/templates/menu.tpl"); - -{* from within Smarty template *} -{include file="file:D:/usr/local/share/templates/navigation.tpl"} - - - - - - Templates from other sources - - You can retrieve templates using whatever possible source you can - access with PHP: databases, sockets, LDAP, and so on. You do this - by writing resource plugin functions and registering them with - Smarty. - - - - See resource plugins - section for more information on the functions you are supposed - to provide. - - - - - Note that you cannot override the built-in - file resource, but you can provide a resource - that fetches templates from the file system in some other way by - registering under another resource name. - - - - using custom resources - -// from PHP script - -// put these function somewhere in your application -function db_get_template ($tpl_name, &tpl_source, &$smarty_obj) -{ - // do database call here to fetch your template, - // populating $tpl_source - $sql = new SQL; - $sql->query("select tpl_source - from my_table - where tpl_name='$tpl_name'"); - if ($sql->num_rows) { - $tpl_source = $sql->record['tpl_source']; - return true; - } else { - return false; - } -} - -function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) -{ - // do database call here to populate $tpl_timestamp. - $sql = new SQL; - $sql->query("select tpl_timestamp - from my_table - where tpl_name='$tpl_name'"); - if ($sql->num_rows) { - $tpl_timestamp = $sql->record['tpl_timestamp']; - return true; - } else { - return false; - } -} - -function db_get_secure($tpl_name, &$smarty_obj) -{ - // assume all templates are secure - return true; -} - -function db_get_trusted($tpl_name, &$smarty_obj) -{ - // not used for templates -} - -// register the resource name "db" -$smarty->register_resource("db", array("db_get_template", - "db_get_timestamp", - "db_get_secure", - "db_get_trusted")); - -// using resource from php script -$smarty->display("db:index.tpl"); - -{* using resource from within Smarty template *} -{include file="db:/extras/navigation.tpl"} - - - - - Default Template Handler Function - - You can specify a function that is used to retrieve template - contents in the event the template cannot be retrieved from its - resource. One use of this is to create templates that do not exist - on-the-fly. - - - using the default template handler function - -// from PHP script - -// put this function somewhere in your application - -function make_template ($resource_type, $resource_name, &$template_source, - &$template_timestamp, &$smarty_obj) { - - if( $resource_type == 'file' ) { - if ( ! is_readable ( $resource_name )) { - // create the template file, return contents. - $template_source = "This is a new template."; - $template_timestamp = time(); - $smarty_obj->_write_file($resource_name,$template_source); - return true; - } - else { - // not a file - return false; - } -} - -// set the default handler -$smarty->default_template_handler_func = 'make_template'; - - - - -