It is undoubtedly one of the most asked questions on the PHP mailing lists: how do I make my PHP scripts independent of the layout? While PHP is billed as "HTML embedded scripting language", after writing a couple of projects that mixed PHP and HTML freely one comes up with the idea that separation of form and content is a Good Thing [TM]. In addition, in many companies the roles of layout designer and programmer are separate. Consequently, the search for a templating solution ensues. In our company for example, the development of an application goes on as follows: After the requirements docs are done, the interface designer makes mockups of the interface and gives them to the programmer. The programmer implements business logic in PHP and uses interface mockups to create skeleton templates. The project is then handed off to the HTML designer/web page layout person who brings the templates up to their full glory. The project may go back and forth between program- ming/HTML a couple of times. Thus, it’s important to have good template support because programmers don’t want anything to do with HTML and don’t want HTML designers mucking around with PHP code. Designers need support for config files, dynamic blocks and other interface issues, but they don’t want to have to deal with intricacies of the PHP programming language. Looking at many templating solutions available for PHP today, most of them provide a rudimentary way of substituting variables into templates and do a limited form of dynamic block functionality. But our needs required a bit more than that. We didn’t want programmers to be dealing with HTML layout at ALL, but this was almost inevitable. For instance, if a designer wanted background colors to alternate on dy- namic blocks, this had to be worked out with the programmer in advance. We also needed designers to be able to use their own configuration files, and pull variables from them into the templates. The list goes on. We started out writing out a spec for a template engine back in late 1999. After fin- ishing the spec, we began to work on a template engine written in C that would hopefully be accepted for inclusion with PHP. Not only did we run into many com- plicated technical barriers, but there was also much heated debate about exactly what a template engine should and should not do. From this experience, we decided that the template engine should be written in PHP as a class, for anyone to use as they see fit. So we wrote an engine that did just that and SmartTemplate came into exis- tence (note: this class was never submitted to the public). It was a class that did al- most everything we wanted: regular variable substitution, supported including other templates, integration with config files, embedding PHP code, limited ’if’ statement functionality and much more robust dynamic blocks which could be multiply nested. It did all this with regular expressions and the code turned out to be rather, shall we say, impenetrable. It was also noticably slow in large applications from all the pars- ing and regular expression work it had to do on each invocation. The biggest problem from a programmer’s point of view was all the necessary work in the PHP script to setup and process templates and dynamic blocks. How do we make this easier? Then came the vision of what ultimately became Smarty. We know how fast PHP code is without the overhead of template parsing. We also know how meticulous and overbearing the PHP language may look to the average designer, and this could be masked with a much simpler templating syntax. So what if we combined the two strengths? Thus, Smarty was born... i, Preface ii,
Chapter 1. What is Smarty?
Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation. This is best described in a situation where the application programmer and the template designer play dif- ferent roles, or in most cases are not the same person. For example, let’s say you are creating a web page that is displaying a newspaper article. The article headline, tagline, author and body are content elements, they contain no information about how they will be presented. They are passed into Smarty by the application, then the template designer edits the templates and uses a combination of HTML tags and tem- plate tags to format the presentation of these elements (HTML tables, background colors, font sizes, style sheets, etc.) One day the programmer needs to change the way the article content is retrieved (a change in application logic.) This change does not affect the template designer, the content will still arrive in the template exactly the same. Likewise, if the template designer wants to completely redesign the tem- plates, this requires no changes to the application logic. Therefore, the programmer can make changes to the application logic without the need to restructure templates, and the template designer can make changes to templates without breaking applica- tion logic. Now for a short word on what Smarty does NOT do. Smarty does not attempt to completely separate logic from the templates. There is no problem with logic in your templates under the condition that this logic is strictly for presentation. A word of advice: keep application logic out of the templates, and presentation logic out of the application. This will most definately keep things manageable and scalable for the foreseeable future. One of the unique aspects about Smarty is the template compling. This means Smarty reads the template files and creates PHP scripts from them. Once they are created, they are executed from then on. Therefore there is no costly template file parsing for each request, and each template can take full advantage of PHP compiler cache solutions such as Zend Accelerator (http://www.zend.com) or PHP Accelerator (http://www.php-accelerator.co.uk). Some of Smarty’s features: • It is extremely fast. • It is efficient since the PHP parser does the dirty work. • No template parsing overhead, only compiles once. • It is smart about recompiling only the template files that have changed. • You can make custom functions and custom variable modifiers, so the template language is extremely extensible. • Configurable template delimiter tag syntax, so you can use {}, {{}}, , etc. • The if/elseif/else/endif constructs are passed to the PHP parser, so the {if ...} ex- pression syntax can be as simple or as complex as you like. • Unlimited nesting of sections, ifs, etc. allowed. • It is possible to embed PHP code right in your template files, although this may not be needed (nor recommended) since the engine is so customizable. • Built-in caching support • Arbitrary template sources • Custom cache handling functions • Plugin architecture, Chapter 1. What is Smarty?,
Chapter 2. Installation Requirements
Smarty requires a web server running PHP 4.0.6 or later.
Basic Installation
Install the Smarty library files which are in the /libs/ directory of the distribution. These are the PHP files that you SHOULD NOT edit. They are shared among all ap- plications and they only get updated when you upgrade to a new version of Smarty. Example 2-1. Smarty library files Smarty.class.php Smarty_Compiler.class.php Config_File.class.php debug.tpl /plugins/*.php (all of them!) Smarty uses a PHP constant named SMARTY_DIR which is the system filepath Smarty library directory. Basically, if your application can find the Smarty.class.php file, you do not need to set SMARTY_DIR, Smarty will figure it out on its own. Therefore, if Smarty.class.php is not in your include_path, or you do not supply an absolute path to it in your application, then you must define SMARTY_DIR manually. SMARTY_DIR must include a trailing slash. Here is how you create an instance of Smarty in your PHP scripts: Example 2-2. Create Smarty instance of Smarty require(’Smarty.class.php’); $smarty = new Smarty; Try running the above script. If you get an error saying the Smarty.class.php file could not be found, you have to do one of the following: Example 2-3. Supply absolute path to library directory require(’/usr/local/lib/php/Smarty/Smarty.class.php’); $smarty = new Smarty; Example 2-4. Add library directory to php_include path // Edit your php.ini file, add the Smarty library // directory to the include_path and restart web server. // Then the following should work: require(’Smarty.class.php’); $smarty = new Smarty; Example 2-5. Set SMARTY_DIR constant manually define(’SMARTY_DIR’,’/usr/local/lib/php/Smarty/’); require(SMARTY_DIR.’Smarty.class.php’); $smarty = new Smarty; Now that the library files are in place, it’s time to setup the Smarty directories for your application. Smarty requires four directories which are (by default) named templates,, Chapter 2. Installation templates_c, configs and cache. Each of these are definable by the Smarty class prop- erties $template_dir, $compile_dir, $config_dir, and $cache_dir respectively. It is highly recommended that you setup a separate set of these directories for each application that will use Smarty. Be sure you know the location of your web server document root. In our example, the document root is "/web/www.mydomain.com/docs/". The Smarty directories are only accessed by the Smarty library and never accessed directly by the web browser. Therefore to avoid any security concerns, it is recommended to place these directories in a directory off the document root. For our installation example, we will be setting up the Smarty environment for a guest book application. We picked an application only for the purpose of a direc- tory naming convention. You can use the same environment for any application, just replace "guestbook" with the name of your app. We’ll place our Smarty directories under "/web/www.mydomain.com/smarty/guestbook/". You will need as least one file under your document root, and that is the script ac- cessed by the web browser. We will call our script "index.php", and place it in a sub- directory under the document root called "/guestbook/". It is convenient to setup the web server so that "index.php" can be identified as the default directory index, so if you access "http://www.mydomain.com/guestbook/", the index.php script will be executed without "index.php" in the URL. In Apache you can set this up by adding "index.php" onto the end of your DirectoryIndex setting (separate each entry with a space.) Lets take a look at the file structure so far: Example 2-6. Example file structure /usr/local/lib/php/Smarty/Smarty.class.php /usr/local/lib/php/Smarty/Smarty_Compiler.class.php /usr/local/lib/php/Smarty/Config_File.class.php /usr/local/lib/php/Smarty/debug.tpl /usr/local/lib/php/Smarty/plugins/*.php /web/www.mydomain.com/smarty/guestbook/templates/ /web/www.mydomain.com/smarty/guestbook/templates_c/ /web/www.mydomain.com/smarty/guestbook/configs/ /web/www.mydomain.com/smarty/guestbook/cache/ /web/www.mydomain.com/docs/guestbook/index.php Smarty will need write access to the $compile_dir and $cache_dir, so be sure the web server user can write to them. This is usually user "nobody" and group "nobody". For OS X users, the default is user "web" and group "web". If you are using Apache, you can look in your httpd.conf file (usually in "/usr/local/apache/conf/") to see what user and group are being used. Example 2-7. Setting file permissions chown nobody:nobody /web/www.mydomain.com/smarty/templates_c/ chmod 770 /web/www.mydomain.com/smarty/templates_c/ chown nobody:nobody /web/www.mydomain.com/smarty/cache/ chmod 770 /web/www.mydomain.com/smarty/cache/ Technical Note: chmod 770 will be fairly tight security, it only allows user "nobody" and group "nobody" read/write access to the directories. If you would like to open up read access to anyone (mostly for your own convenience of viewing these files), you can use 775 instead., Chapter 2. Installation We need to create the index.tpl file that Smarty will load. This will be located in your $template_dir. Example 2-8. Editing /web/www.mydomain.com/smarty/templates/index.tpl {* Smarty *} Hello, {$name}! Technical Note: {* Smarty *} is a template comment. It is not required, but it is good prac- tice to start all your template files with this comment. It makes the file easy to recognize regardless of the file extension. For example, text editors could recognize the file and turn on special syntax highlighting. Now lets edit index.php. We’ll create an instance of Smarty, assign a template variable and display the index.tpl file. In our example environment, "/usr/local/lib/php/Smarty" is in our include_path. Be sure you do the same, or use absolute paths. Example 2-9. Editing /web/www.mydomain.com/docs/guestbook/index.php // load Smarty library require(’Smarty.class.php’); $smarty = new Smarty; $smarty->template_dir = ’/web/www.mydomain.com/smarty/guestbook/templates/’; $smarty->compile_dir = ’/web/www.mydomain.com/smarty/guestbook/templates_c/’; $smarty->config_dir = ’/web/www.mydomain.com/smarty/guestbook/configs/’; $smarty->cache_dir = ’/web/www.mydomain.com/smarty/guestbook/cache/’; $smarty->assign(’name’,’Ned’); $smarty->display(’index.tpl’); Technical Note: In our example, we are setting absolute paths to all of the Smarty direc- tories. If ’/web/www.mydomain.com/smarty/guestbook/’ is within your PHP include_path, then these settings are not necessary. However, it is more efficient and (from experience) less error-prone to set them to absolute paths. This ensures that Smarty is getting files from the directories you intended. Now load the index.php file from your web browser. You should see "Hello, Ned!" You have completed the basic setup for Smarty!
Extended Setup
This is a continuation of the basic installation, please read that first! A slightly more flexible way to setup Smarty is to extend the class and initialize your Smarty environment. So instead of repeatedly setting directory paths, assign- ing the same vars, etc., we can do that in one place. Lets create a new directory "/php/includes/guestbook/" and make a new file called "setup.php". In our exam- ple environment, "/php/includes" is in our include_path. Be sure you set this up too, or use absolute file paths., Chapter 2. Installation Example 2-10. Editing /php/includes/guestbook/setup.php // load Smarty library require(’Smarty.class.php’); // The setup.php file is a good place to load // required application library files, and you // can do that right here. An example: // require(’guestbook/guestbook.lib.php’); class Smarty_GuestBook extends Smarty { function Smarty_GuestBook() { // Class Constructor. These automatically get set with each new instance. $this->Smarty(); $this->template_dir = ’/web/www.mydomain.com/smarty/guestbook/templates/’; $this->compile_dir = ’/web/www.mydomain.com/smarty/guestbook/templates_c/’; $this->config_dir = ’/web/www.mydomain.com/smarty/guestbook/configs/’; $this->cache_dir = ’/web/www.mydomain.com/smarty/guestbook/cache/’; $this->caching = true; $this->assign(’app_name’,’Guest Book’); } } Now lets alter the index.php file to use setup.php: Example 2-11. Editing /web/www.mydomain.com/docs/guestbook/index.php require(’guestbook/setup.php’); $smarty = new Smarty_GuestBook; $smarty->assign(’name’,’Ned’); $smarty->display(’index.tpl’); Now you see it is quite simple to bring up an instance of Smarty, just use Smarty_GuestBook which automatically initializes everything for our application.,
Chapter 3. Basic Syntax
All Smarty template tags are enclosed within delimiters. By default, these delimiters are { and }, but they can be changed. For these examples, we will assume that you are using the default delimiters. In Smarty, all content outside of delimiters is displayed as static content, or unchanged. When Smarty encounters template tags, it attempts to interpret them, and displays the appropriate output in their place.
Comments
Template comments are surrounded by asterisks, and that is surrounded by the de- limiter tags like so: {* this is a comment *} Smarty comments are not displayed in the final output of the template. They are used for making internal notes in the templates. Example 3-1. Comments {* Smarty *} {* include the header file here *} {include file="header.tpl"} {include file=$includeFile} {include file=#includeFile#} {* display dropdown lists *}
Functions
Each Smarty tag either prints a variable or invokes some sort of function. Functions are processed and displayed by enclosing the function and its attributes into delim- iters like so: {funcname attr1="val" attr2="val"}. Example 3-2. function syntax {config_load file="colors.conf"} {include file="header.tpl"} {if $name eq "Fred"} You are not allowed here {else} Welcome, {$name}! {/if} {include file="footer.tpl"} Both built-in functions and custom functions have the same syntax in the templates. Built-in functions are the inner workings of Smarty, such as if, section and strip. They cannot be modified. Custom functions are additional functions implemented via plu- gins. They can be modified to your liking, or you can add new ones. html_options and html_select_date are examples of custom functions., Chapter 3. Basic Syntax
Attributes
Most of the functions take attributes that specify or modify their behavior. Attributes to Smarty functions are much like HTML attributes. Static values don’t have to be enclosed in quotes, but it is recommended for literal strings. Variables may also be used, and should not be in quotes. Some attributes require boolean values (true or false). These can be specified as either unquoted true, on, and yes, or false, off, and no. Example 3-3. function attribute syntax {include file="header.tpl"} {include file=$includeFile} {include file=#includeFile#} {html_select_date display_days=yes}
Embedding Vars in Double Quotes
Smarty will recognize assigned variables embedded in double quotes so long as the variables contain only numbers, letters, underscores and brackets []. With any other characters (period, object reference, etc.) the variable must be surrounded by back- ticks. Example 3-4. embedded quotes syntax SYNTAX EXAMPLES: {func var="test $foo test"} <- sees $foo {func var="test $foo_bar test"} <- sees $foo_bar {func var="test $foo[0] test"} <- sees $foo[0] {func var="test $foo[bar] test"} <- sees $foo[bar] {func var="test $foo.bar test"} <- sees $foo (not $foo.bar) {func var="test ‘$foo.bar‘ test"} <- sees $foo.bar PRACTICAL EXAMPLES: {include file="subdir/$tpl_name.tpl"} <- will replace $tpl_name with value {cycle values="one,two,‘$smarty.config.myval‘"} <- must have backticks,
Chapter 4. Variables
Smarty has several different types of variables. The type of the variable depends on what symbol it is prefixed with (or enclosed within). Variables in Smarty can be either displayed directly or used as arguments for func- tion attributes and modifiers, inside conditional expressions, etc. To print a variable, simply enclose it in the delimiters so that it is the only thing contained between them. Examples: {$Name} {$Contacts[row].Phone}
Variables assigned from PHP
Variables that are assigned from PHP are referenced by preceding them with a dollar sign $. Variables assigned from within the template with the assign function are also displayed this way. Example 4-1. assigned variables Hello {$firstname}, glad to see you could make it.
Your last login was on {$lastLoginDate}. OUTPUT: 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 assigned from PHP by specifying the key after the ’.’ (period) symbol. Example 4-2. accessing associative array variables index.php: $smarty = new Smarty; $smarty->assign(’Contacts’, array(’fax’ => ’555-222-9876’, ’email’ => ’email is hidden’, ’phone’ => array(’home’ => ’555-444-3333’, ’cell’ => ’555-111-1234’))); $smarty->display(’index.tpl’); index.tpl: {$Contacts.fax} {$Contacts.email} {* you can print arrays of arrays as well *} {$Contacts.phone.home} {$Contacts.phone.cell} OUTPUT:, Chapter 4. Variables 555-222-9876 email is hidden 555-444-3333 555-111-1234
Array indexes
You can reference arrays by their index, much like native PHP syntax. Example 4-3. accessing arrays by index index.php: $smarty = new Smarty; $smarty->assign(’Contacts’, array(’555-222-9876’, ’email is hidden’, array(’555-444-3333’, ’555-111-1234’))); $smarty->display(’index.tpl’); index.tpl: {$Contacts[0]} {$Contacts[1]} {* you can print arrays of arrays as well *} {$Contacts[2][0]} {$Contacts[2][1]} OUTPUT: 555-222-9876 email is hidden 555-444-3333 555-111-1234
Objects
Properties of objects assigned from PHP can be referenced by specifying the property name after the ’->’ symbol. Example 4-4. accessing object properties name: {$person->name} email: {$person->email} OUTPUT: name: Zaphod Beeblebrox email: email is hidden , Chapter 4. Variables
Variables loaded from config files
Variables that are loaded from the config files are referenced by enclosing them within hash marks (#), or with the smarty variable $smarty.config. The second syntax is use- ful for embedding into quoted attribute values. Example 4-5. config variables foo.conf: pageTitle = "This is mine" bodyBgColor = "#eeeeee" tableBorderSize = "3" tableBgColor = "#bbbbbb" rowBgColor = "#cccccc" index.tpl: {config_load file="foo.conf"} {#pageTitle#}
, Chapter 4. Variables 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. {$smarty} reserved variable The reserved {$smarty} variable can be used to access several special template vari- ables. The full list of them follows.
Request variables
The request variables such as get, post, cookies, server, environment, and session variables can be accessed as demonstrated in the examples below: Example 4-6. displaying request variables {* display value of page from URL (GET) http://www.domain.com/index.php?page=foo *} {$smarty.get.page} {* display the variable "page" from a form a form (POST) *} {$smarty.post.page} {* display the value of the cookie "username" *} {$smarty.cookies.username} {* display the server variable "SERVER_NAME" *} {$smarty.server.SERVER_NAME} {* display the system environment variable "PATH" *} {$smarty.env.PATH} {* display the php session variable "id" *} {$smarty.session.id} {* display the variable "username" from merged get/post/cookies/server/env *} {$smarty.request.username} {$smarty.now} The current timestamp can be accessed with {$smarty.now}. The number reflects the number of seconds passed since the so-called Epoch (January 1, 1970) and can be passed directly to date_format modifier for display purposes. Example 4-7. using {$smarty.now} {* use the date_format modifier to show current date and time *} {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} {$smarty.const} You can access PHP constant values directly. Example 4-8. using {$smarty.const} {$smarty.const._MY_CONST_VAL}, Chapter 4. Variables {$smarty.capture} The output captured via {capture}..{/capture} construct can be accessed using {$smarty} variable. See section on capture for an example. {$smarty.config} {$smarty} variable can be used to refer to loaded config variables. {$smarty.config.foo} is a synonyn for {#foo#}. See the section on config_load for an example. {$smarty.section}, {$smarty.foreach} {$smarty} variable can be used to refer to ’section’ and ’foreach’ loop properties. See docs for section and foreach. {$smarty.template} This variable contains the name of the current template being processed., Chapter 4. Variables,
Chapter 5. Variable Modifiers
Variable modifiers can be applied to variables, custom functions or strings. To ap- ply a modifier, specify the value 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). Example 5-1. modifier example {* Uppercase the title *}
{$title|upper}
{* Truncate the topic to 40 characters use ... at the end *} Topic: {$topic|truncate:40:"..."} {* format a literal string *} {"now"|date_format:"%Y/%m/%d"} {* apply modifier to a custom function *} {mailto|upper address="email is hidden"} 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.) capitalize This is used to capitalize the first letter of all words in a variable. Example 5-2. capitalize index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Police begin campaign to rundown jaywalkers.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|capitalize} OUTPUT: Police begin campaign to rundown jaywalkers. Police Begin Campaign To Rundown Jaywalkers. count_characters This is used to count the number of characters in a variable., Chapter 5. Variable Modifiers Example 5-3. count_characters index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Cold Wave Linked to Temperatures.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|count_characters} OUTPUT: Cold Wave Linked to Temperatures. cat Parameter Type Required cat Description Position 1 string No empty This value to catentate to the given variable. This value is catenated to the given variable. Example 5-4. cat index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Psychics predict world didn’t end’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle|cat:" yesterday."} OUTPUT: Psychics predict world didn’t end yesterday. count_paragraphs This is used to count the number of paragraphs in a variable. Example 5-5. count_paragraphs index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’War Dims Hope for Peace. Child’s Death Ru- ins Couple’s Holiday.’); $smarty->display(’index.tpl’); index.tpl:, Chapter 5. Variable Modifiers {$articleTitle} {$articleTitle|count_paragraphs} OUTPUT: War Dims Hope for Peace. Child’s Death Ruins Couple’s Holiday. Man is Fatally Slain. Death Causes Loneliness, Feeling of Isolation. count_sentences This is used to count the number of sentences in a variable. Example 5-6. count_sentences index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Two Soviet Ships Collide - One Dies. En- raged Cow Injures Farmer with Axe.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|count_sentences} OUTPUT: Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe. count_words This is used to count the number of words in a variable. Example 5-7. count_words index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Dealers Will Hear Car Talk at Noon.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|count_words} OUTPUT: Dealers Will Hear Car Talk at Noon. date_format, Chapter 5. Variable Modifiers Parameter Type Required Default Description Position 1 string No %b %e, %Y This is the format for the outputted date. 2 string No n/a This is the default date if the input is empty. This formats a date and time into the given strftime() format. Dates can be passed to Smarty as unix timestamps, mysql timestamps or any string made up of month day year (parsable by strtotime). Designers can then use date_format to have complete control of the formatting of the date. If the date passed to date_format is empty and a second parameter is passed, that will be used as the date to format. Example 5-8. date_format index.php: $smarty = new Smarty; $smarty->assign(’yesterday’, strtotime(’-1 day’)); $smarty->display(’index.tpl’); index.tpl: {$smarty.now|date_format} {$smarty.now|date_format:"%A, %B %e, %Y"} {$smarty.now|date_format:"%H:%M:%S"} {$yesterday|date_format} {$yesterday|date_format:"%A, %B %e, %Y"} {$yesterday|date_format:"%H:%M:%S"} OUTPUT: Feb 6, 2001 Tuesday, February 6, 2001 14:33:00 Feb 5, 2001 Monday, February 5, 2001 14:33:00 Example 5-9. date_format conversion specifiers %a - abbreviated weekday name according to the current locale %A - full weekday name according to the current locale %b - abbreviated month name according to the current locale %B - full month name according to the current locale %c - preferred date and time representation for the current locale %C - century number (the year divided by 100 and truncated to an inte- ger, range 00 to 99) %d - day of the month as a decimal number (range 00 to 31) %D - same as %m/%d/%y, Chapter 5. Variable Modifiers %e - day of the month as a decimal number, a single digit is preceded by a space (range 1 to 31) %g - Week-based year within century [00,99] %G - Week-based year, including the century [0000,9999] %h - same as %b %H - hour as a decimal number using a 24-hour clock (range 00 to 23) %I - hour as a decimal number using a 12-hour clock (range 01 to 12) %j - day of the year as a decimal number (range 001 to 366) %k - Hour (24-hour clock) single digits are preceded by a blank. (range 0 to 23) %l - hour as a decimal number using a 12-hour clock, single digits pre- ceeded by a space (range 1 to 12) %m - month as a decimal number (range 01 to 12) %M - minute as a decimal number %n - newline character %p - either ‘am’ or ‘pm’ according to the given time value, or the cor- responding strings for the current locale %r - time in a.m. and p.m. notation %R - time in 24 hour notation %S - second as a decimal number %t - tab character %T - current time, equal to %H:%M:%S %u - weekday as a decimal number [1,7], with 1 representing Monday %U - week number of the current year as a decimal number, starting with the first Sun- day as the first day of the first week %V - The ISO 8601:1988 week number of the current year as a decimal num- ber, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Mon- day as the first day of the week. %w - day of the week as a decimal, Sunday being 0 %W - week number of the current year as a decimal number, starting with the first Mon- day as the first day of the first week %x - preferred date representation for the current locale without the time %X - preferred time representation for the current locale without the date %y - year as a decimal number without a century (range 00 to 99) %Y - year as a decimal number including the century %Z - time zone or name or abbreviation %% - a literal ‘%’ character, Chapter 5. Variable Modifiers PROGRAMMERS NOTE: date_format is essentially a wrapper to PHP’s strftime() function. You may have more or less conversion specifiers available depending on your system’s strftime() function where PHP was compiled. Check your system’s manpage for a full list of valid specifiers. default Parameter Type Required Default Description Position 1 string No empty This is the default value to output if the variable is empty. This is used to set a default value for a variable. If the variable is empty or unset, the given default value is printed instead. Default takes one argument. Example 5-10. default index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Dealers Will Hear Car Talk at Noon.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle|default:"no title"} {$myTitle|default:"no title"} OUTPUT: Dealers Will Hear Car Talk at Noon. no title escape Parameter Type Required Possible Default Description Position Values 1 string No html This is the html,htmlall,url,quotes,hex,heesxcaepnetity,javascript format to use. This is used to html escape, url escape, escape single quotes on a variable not already escaped, hex escape, hexentity or javascript escape. By default, the variable is html escaped. Example 5-11. escape index.php:, Chapter 5. Variable Modifiers $smarty = new Smarty; $smarty->assign(’articleTitle’, "’Stiff Opposition Expected to Casket- less Funeral Plan’"); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|escape} {$articleTitle|escape:"html"} {* escapes & " ’ < > *} {$articleTitle|escape:"htmlall"} {* escapes ALL html entities *} {$articleTitle|escape:"url"} {$articleTitle|escape:"quotes"} {$EmailAddress|escape:"hexentity"} OUTPUT: ’Stiff Opposition Expected to Casketless Funeral Plan’ ’Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan’ ’Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan’ ’Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan’ ’Stiff+Opposition+Expected+to+Casketless+Funeral+Plan’ \’Stiff Opposition Expected to Casketless Funeral Plan\’ bob@me.net indent Parameter Type Required Default Description Position 1 integer No 4 This determines how many characters to indent to. 2 string No (one space) This is the character used to indent with. This indents a string at each line, default is 4. As an optional parameter, you can specify the number of characters to indent. As an optional second parameter, you can specify the character to use to indent with. (Use "\t" for tabs.) Example 5-12. indent index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’NJ judge to rule on nude beach.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|indent} {$articleTitle|indent:10} {$articleTitle|indent:1:"\t"}, Chapter 5. Variable Modifiers OUTPUT: NJ judge to rule on nude beach. Sun or rain expected today, dark tonight. Statistics show that teen pregnancy drops off significantly after 25. NJ judge to rule on nude beach. Sun or rain expected today, dark tonight. Statistics show that teen pregnancy drops off significantly after 25. NJ judge to rule on nude beach. Sun or rain expected today, dark tonight. Statistics show that teen pregnancy drops off significantly af- ter 25. NJ judge to rule on nude beach. Sun or rain expected today, dark tonight. Statistics show that teen pregnancy drops off significantly after 25. lower This is used to lowercase a variable. Example 5-13. lower index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Two Convicts Evade Noose, Jury Hung.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|lower} OUTPUT: Two Convicts Evade Noose, Jury Hung. two convicts evade noose, jury hung. nl2br All linebreaks will be converted to tags in the given variable. This is equiva- lent to the PHP nl2br() function. Example 5-14. nl2br index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Sun or rain expected\ntoday, dark tonight"); $smarty->display(’index.tpl’); index.tpl: {$articleTitle|nl2br} OUTPUT:, Chapter 5. Variable Modifiers Sun or rain expected today, dark tonight regex_replace Parameter Type Required Default Description Position 1 string Yes n/a This is the regular expression to be replaced. 2 string Yes n/a This is the string of text to replace with. A regular expression search and replace on a variable. Use the syntax for preg_replace() from the PHP manual. Example 5-15. regex_replace index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Infertility unlikely to\nbe passed on, ex- perts say."); $smarty->display(’index.tpl’); index.tpl: {* replace each carriage return, tab & new line with a space *} {$articleTitle} {$articleTitle|regex_replace:"/[\r\t\n]/":" "} OUTPUT: Infertility unlikely to be passed on, experts say. Infertility unlikely to be passed on, experts say. replace Parameter Type Required Default Description Position 1 string Yes n/a This is the string of text to be replaced. 2 string Yes n/a This is the string of text to replace with. A simple search and replace on a variable., Chapter 5. Variable Modifiers Example 5-16. replace index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Child’s Stool Great for Use in Garden."); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|replace:"Garden":"Vineyard"} {$articleTitle|replace:" ":" "} OUTPUT: Child’s Stool Great for Use in Garden. Child’s Stool Great for Use in Vineyard. Child’s Stool Great for Use in Garden. spacify Parameter Type Required Default Description Position 1 string No one space This what gets inserted between each character of the variable. spacify is a way to insert a space between every character of a variable. You can optionally pass a different character (or string) to insert. Example 5-17. spacify index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Something Went Wrong in Jet Crash, Ex- perts Say.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|spacify} {$articleTitle|spacify:"^^"} OUTPUT: Something Went Wrong in Jet Crash, Experts Say. SomethingWentWronginJetCrash, ExpertsSay. S^^o^^m^^e^^t^^h^^i^^n^^g^^ ^^W^^e^^n^^t^^ ^^W^^r^^o^^n^^g^^ ^^i^^n^^ ^^J^^e^^t^^ ^^C^^r^^a^^s^^h^^,^^ ^^E^^x^^p^^e^^r^^t^^s^^ ^^S^^a^^y^^. string_format, Chapter 5. Variable Modifiers Parameter Type Required Default Description Position 1 string Yes n/a This is what format to use. (sprintf) This is a way to format strings, such as decimal numbers and such. Use the syntax for sprintf for the formatting. Example 5-18. string_format index.php: $smarty = new Smarty; $smarty->assign(’number’, 23.5787446); $smarty->display(’index.tpl’); index.tpl: {$number} {$number|string_format:"%.2f"} {$number|string_format:"%d"} OUTPUT: 23.5787446 23.58 strip This replaces all repeated spaces, newlines and tabs with a single space, or with a supplied string. Note: If you want to strip blocks of template text, use the strip function. Example 5-19. strip index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Grandmother of\neight makes\t hole in one."); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|strip} {$articleTitle|strip:" "} OUTPUT: Grandmother of eight makes hole in one. Grandmother of eight makes hole in one. Grandmother of eight makes hole in one., Chapter 5. Variable Modifiers strip_tags This strips out markup tags, basically anything between < and >. Example 5-20. strip_tags index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Blind Woman Gets New Kidney from Dad she Hasn’t Seen in years."); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|strip_tags} OUTPUT: Blind Woman Gets New Kidney from Dad she Hasn’t Seen in years. Blind Woman Gets New Kidney from Dad she Hasn’t Seen in years. truncate Parameter Type Required Default Description Position 1 integer No 80 This determines how many characters to truncate to. 2 string No ... This is the text to append if truncation occurs. 3 boolean No false This determines whether or not to truncate at a word boundary (false), or at the exact character (true). This truncates a variable to a character length, default is 80. As an optional second pa- rameter, you can specify a string of text to display at the end if the variable was trun- cated. The characters in the string are included with the original truncation length. By default, truncate will attempt to cut off at a word boundary. If you want to cut off at the exact character length, pass the optional third parameter of true. Example 5-21. truncate index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Two Sisters Reunite after Eighteen Years at Check- out Counter.’); $smarty->display(’index.tpl’); index.tpl:, Chapter 5. Variable Modifiers {$articleTitle} {$articleTitle|truncate} {$articleTitle|truncate:30} {$articleTitle|truncate:30:""} {$articleTitle|truncate:30:"-"} {$articleTitle|truncate:30:"":true} {$articleTitle|truncate:30:"...":true} OUTPUT: Two Sisters Reunite after Eighteen Years at Checkout Counter. Two Sisters Reunite after Eighteen Years at Checkout Counter. Two Sisters Reunite after... Two Sisters Reunite after Two Sisters Reunite after- Two Sisters Reunite after Eigh Two Sisters Reunite after E... upper This is used to uppercase a variable. Example 5-22. upper index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "If Strike isn’t Settled Quickly it may Last a While."); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|upper} OUTPUT: If Strike isn’t Settled Quickly it may Last a While. IF STRIKE ISN’T SETTLED QUICKLY IT MAY LAST A WHILE. wordwrap Parameter Type Required Default Description Position 1 integer No 80 This determines how many columns to wrap to. 2 string No \n This is the string used to wrap words with., Chapter 5. Variable Modifiers Parameter Type Required Default Description Position 3 boolean No false This determines whether or not to wrap at a word boundary (false), or at the exact character (true). This wraps a string to a column width, default is 80. As an optional second parameter, you can specify a string of text to wrap the text to the next line (default is carriage return \n). By default, wordwrap will attempt to wrap at a word boundary. If you want to cut off at the exact character length, pass the optional third parameter of true. Example 5-23. wordwrap index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, "Blind woman gets new kidney from dad she hasn’t seen in years."); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|wordwrap:30} {$articleTitle|wordwrap:20} {$articleTitle|wordwrap:30:" \n"} {$articleTitle|wordwrap:30:"\n":true} OUTPUT: Blind woman gets new kidney from dad she hasn’t seen in years. Blind woman gets new kidney from dad she hasn’t seen in years. Blind woman gets new kidney from dad she hasn’t seen in years. Blind woman gets new kidney from dad she hasn’t seen in years. Blind woman gets new kidney fr om dad she hasn’t seen in year s.,
Chapter 6. Combining Modifiers
You can apply any number of modifiers to a variable. They will be applied in the order they are combined, from left to right. They must be separated with a | (pipe) character. Example 6-1. combining modifiers index.php: $smarty = new Smarty; $smarty->assign(’articleTitle’, ’Smokers are Productive, but Death Cuts Efficiency.’); $smarty->display(’index.tpl’); index.tpl: {$articleTitle} {$articleTitle|upper|spacify} {$articleTitle|lower|spacify|truncate} {$articleTitle|lower|truncate:30|spacify} {$articleTitle|lower|spacify|truncate:30:".."} OUTPUT: Smokers are Productive, but Death Cuts Efficiency. SMOKERSAREPRODUCTIVE, BUTDEATHCUTSEFFICIENCY. smokersareproductive, butdeathcuts... smokersareproductive, but.smokersarep.., Chapter 6. Combining Modifiers,
Chapter 7. Built-in Functions
Smarty comes with several built-in functions. Built-in functions are integral to the template language. You cannot create custom functions with the same names, nor can you modify built-in functions. capture capture is used to collect the output of the template into a variable instead of dis- playing it. Any content between {capture name="foo"} and {/capture} is collected into the variable specified in the name attribute. The captured content can be used in the template from the special variable $smarty.capture.foo where foo is the value passed in the name attribute. If you do not supply a name attribute, then "default" will be used. All {capture} commands must be paired with {/capture}. You can nest capture commands. Technical Note: Smarty 1.4.0 - 1.4.4 placed the captured content into the variable named $return. As of 1.4.5, this behavior was changed to use the name attribute, so update your templates accordingly.
Caution
Be careful when capturing insert output. If you have caching turned on and you have insert commands that you expect to run within cached content, do not capture this content. Example 7-1. capturing template content {* we don’t want to print a table row unless content is displayed *} {capture name=banner} {include file="get_banner.tpl"} {/capture} {if $smarty.capture.banner ne ""}
{$smarty.capture.banner}
{/if} config_load Attribute Name Type Required Default Description file string Yes n/a The name of the config file to include section string No n/a The name of the section to load, Chapter 7. Built-in Functions Attribute Name Type Required Default Description scope string no local How the scope of the loaded variables are treated, which must be one of local, parent or global. local means variables are loaded into the local template context. parent means variables are loaded into both the local context and the parent template that called it. global means variables are available to all templates. global boolean No No Whether or not variables are visible to the parent template, same as scope=parent. NOTE: This attribute is deprecated by the scope attribute, but still supported. If scope is supplied, this value is ignored. This function is used for loading in variables from a configuration file into the tem- plate. See Config Files for more info. Example 7-2. function config_load {config_load file="colors.conf"} {#pageTitle#}
First
Last
Address
, Chapter 7. Built-in Functions Config files may also contain sections. You can load variables from within a section with the added attribute section. NOTE: Config file sections and the built-in template function called section have noth- ing to do with each other, they just happen to share a common naming convention. Example 7-3. function config_load with section {config_load file="colors.conf" section="Customer"} {#pageTitle#}
First
Last
Address
foreach,foreachelse Attribute Name Type Required Default Description from string Yes n/a The name of the array you are looping through item string Yes n/a The name of the variable that is the current element key string No n/a The name of the variable that is the current key name string No n/a The name of the foreach loop for accessing foreach properties foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. The syntax for foreach is much easier than section, but as a tradeoff it can only be used for a single array. foreach tags must be paired with /foreach tags. Required parameters are from and item. The name of the foreach loop can be any- thing you like, made up of letters, numbers and underscores. foreach loops can be nested, and the nested foreach names must be unique from each other. The from vari- able (usually an array of values) determines the number of times foreach will loop. foreachelse is executed when there are no values in the from variable., Chapter 7. Built-in Functions Example 7-4. foreach {* this example will print out all the values of the $custid array *} {foreach from=$custid item=curr_id} id: {$curr_id} {/foreach} OUTPUT: id: 1000 id: 1001 id: 1002 Example 7-5. foreach key {* The key contains the key for each looped value assignment looks like this: $smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"), array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760- 1234"))); *} {foreach name=outer item=contact from=$contacts} {foreach key=key item=item from=$contact} {$key}: {$item} {/foreach} {/foreach} OUTPUT: phone: 1 fax: 2 cell: 3 phone: 555-4444 fax: 555-3333 cell: 760-1234 include Attribute Name Type Required Default Description file string Yes n/a The name of the template file to include assign string No n/a The name of the variable that the output of include will be assigned to [var ...] [var type] No n/a variable to pass local to template Include tags are used for including other templates in the current template. Any vari- ables available in the current template are also available within the included tem- plate. The include tag must have the attribute "file", which contains the template, Chapter 7. Built-in Functions resource path. You can optionally pass the assign attribute, which will specify a template variable name that the output of include will be assigned to instead of displayed. Example 7-6. function include {include file="header.tpl"} {* body of template goes here *} {include file="footer.tpl"} You can also pass variables to included templates as attributes. Any variables explic- itly passed to an included template as attributes are only available within the scope of the included file. Attribute variables override current template variables, in the case they are named alike. Example 7-7. function include passing variables {include file="header.tpl" title="Main Menu" table_bgcolor="#c0c0c0"} {* body of template goes here *} {include file="footer.tpl" logo="http://my.domain.com/logo.gif"} Use the syntax for template resources to include files outside of the $template_dir directory. Example 7-8. function include template resource examples {* absolute filepath *} {include file="/usr/local/include/templates/header.tpl"} {* absolute filepath (same thing) *} {include file="file:/usr/local/include/templates/header.tpl"} {* windows absolute filepath (MUST use "file:" prefix) *} {include file="file:C:/www/pub/templates/header.tpl"} {* include from template resource named "db" *} {include file="db:header.tpl"} include_php Attribute Name Type Required Default Description file string Yes n/a The name of the php file to include once boolean No true whether or not to include the php file more than once if included multiple times, Chapter 7. Built-in Functions Attribute Name Type Required Default Description assign string No n/a The name of the variable that the output of include_php will be assigned to include_php tags are used to include a php script in your template. If security is en- abled, then the php script must be located in the $trusted_dir path. The include_php tag must have the attribute "file", which contains the path to the included php file, either relative to $trusted_dir, or an absolute path. include_php is a nice way to handle componentized templates, and keep PHP code separate from the template files. Lets say you have a template that shows your site navigation, which is pulled dynamically from a database. You can keep your PHP logic that grabs database content in a separate directory, and include it at the top of the template. Now you can include this template anywhere without worrying if the database information was assigned by the application before hand. By default, php files are only included once even if called multiple times in the tem- plate. You can specify that it should be included every time with the once attribute. Setting once to false will include the php script each time it is included in the tem- plate. You can optionally pass the assign attribute, which will specify a template variable name that the output of include_php will be assigned to instead of displayed. The smarty object is available as $this within the PHP script that you include. Example 7-9. function include_php load_nav.php - query("select * from site_nav_sections order by name",SQL_ALL); $this->assign(’sections’,$sql->record); ?> index.tpl - {* absolute path, or relative to $trusted_dir *} {include_php file="/path/to/load_nav.php"} {foreach item="curr_section" from=$sections} {$curr_section.name} {/foreach} insert, Chapter 7. Built-in Functions Attribute Name Type Required Default Description name string Yes n/a The name of the insert function (insert_name) assign string No n/a The name of the template variable the output will be assigned to script string No n/a The name of the php script that is included before the insert function is called [var ...] [var type] No n/a variable to pass to insert function Insert tags work much like include tags, except that insert tags are not cached when you have template caching enabled. They will be executed on every invocation of the template. Let’s say you have a template with a banner slot at the top of the page. The banner can contain any mixture of HTML, images, flash, etc. so we can’t just use a static link here, and we don’t want this contents cached with the page. In comes the insert tag: the template knows #banner_location_id# and #site_id# values (gathered from a config file), and needs to call a function to get the banner contents. Example 7-10. function insert {* example of fetching a banner *} {insert name="getBanner" lid=#banner_location_id# sid=#site_id#} In this example, we are using the name "getBanner" and passing the parameters #banner_location_id# and #site_id#. Smarty will look for a function named insert_getBanner() in your PHP application, passing the values of #banner_location_id# and #site_id# as the first argument in an associative array. All insert function names in your application must be prepended with "insert_" to remedy possible function name-space conflicts. Your insert_getBanner() function should do something with the passed values and return the results. These results are then displayed in the template in place of the insert tag. In this example, Smarty would call this function: insert_getBanner(array("lid" => "12345","sid" => "67890")); and display the returned results in place of the insert tag. If you supply the "assign" attribute, the output of the insert tag will be assigned to this template variable instead of being output to the template. NOTE: assigning the output to a template variable isn’t too useful with caching enabled. If you supply the "script" attribute, this php script will be included (only once) before the insert function is executed. This is the case where the insert function may not exist yet, and a php script must be included first to make it work. The path can be either absolute, or relative to $trusted_dir. When security is enabled, the script must reside in $trusted_dir. The Smarty object is passed as the second argument. This way you can reference and modify information in the Smarty object from within the insert function., Chapter 7. Built-in Functions Technical Note: It is possible to have portions of the template not cached. If you have caching turned on, insert tags will not be cached. They will run dynamically every time the page is created, even within cached pages. This works good for things like banners, polls, live weather, search results, user feedback areas, etc. if,elseif,else if statements in Smarty have much the same flexibility as php if statements, with a few added features for the template engine. Every if must be paired with an /if . else and elseif are also permitted. "eq", "ne","neq", "gt", "lt", "lte", "le", "gte" "ge","is even","is odd", "is not even","is not odd","not","mod","div by","even by","odd by","==","!=",">", "<","<=",">=" are all valid conditional qualifiers, and must be separated from sur- rounding elements by spaces. Example 7-11. if statements {if $name eq "Fred"} Welcome Sir. {elseif $name eq "Wilma"} Welcome Ma’am. {else} Welcome, whatever you are. {/if} {* an example with "or" logic *} {if $name eq "Fred" or $name eq "Wilma"} ... {/if} {* same as above *} {if $name == "Fred" || $name == "Wilma"} ... {/if} {* the following syntax will NOT work, conditional qualifiers must be separated from surrounding elements by spaces *} {if $name=="Fred" || $name=="Wilma"} ... {/if} {* parenthesis are allowed *} {if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#} ... {/if} {* you can also embed php function calls *} {if count($var) gt 0} ... {/if} {* test if values are even or odd *} {if $var is even} ... {/if} {if $var is odd} ... {/if} {if $var is not odd} ... {/if}, Chapter 7. Built-in Functions {* test if var is divisible by 4 *} {if $var is div by 4} ... {/if} {* test if var is even, grouped by two. i.e., 0=even, 1=even, 2=odd, 3=odd, 4=even, 5=even, etc. *} {if $var is even by 2} ... {/if} {* 0=even, 1=even, 2=even, 3=odd, 4=odd, 5=odd, etc. *} {if $var is even by 3} ... {/if} ldelim,rdelim ldelim and rdelim are used for displaying the literal delimiter, in our case "{" or "}". The template engine always tries to interpret delimiters, so this is the way around that. Example 7-12. ldelim, rdelim {* this will print literal delimiters out of the template *} {ldelim}funcname{rdelim} is how functions look in Smarty! OUTPUT: {funcname} is how functions look in Smarty! literal Literal tags allow a block of data to be taken literally, not being interpreted by the Smarty engine. This is handy for things like javascript sections, where there maybe curly braces and such things that would confuse the template parser. Anything within {literal}{/literal} tags is not interpreted, but displayed as-is. Example 7-13. literal tags {literal} {/literal}, Chapter 7. Built-in Functions php php tags allow php to be embedded directly into the template. They will not be es- caped, regardless of the $php_handling setting. This is for advanced users only, not normally needed. Example 7-14. php tags {php} // including a php script directly // from the template. include("/path/to/display_weather.php"); {/php} section,sectionelse Attribute Name Type Required Default Description name string Yes n/a The name of the section loop [$vari- Yes n/a The name of the able_name] variable to determine # of loop iterations start integer No 0 The index position that the section will begin looping. If the value is negative, the start position is calculated from the end of the array. For example, if there are seven values in the loop array and start is -2, the start index is 5. Invalid values (values outside of the length of the loop array) are automatically truncated to the closest valid value., Chapter 7. Built-in Functions Attribute Name Type Required Default Description step integer No 1 The step value that will be used to traverse the loop array. For example, step=2 will loop on index 0,2,4, etc. If step is negative, it will step through the array backwards. max integer No 1 Sets the maximum number of times the section will loop. show boolean No true determines whether or not to show this section Template sections are used for looping over arrays of data. All section tags must be paired with /section tags. Required parameters are name and loop. The name of the section can be anything you like, made up of letters, numbers and underscores. Sec- tions can be nested, and the nested section names must be unique from each other. The loop variable (usually an array of values) determines the number of times the section will loop. When printing a variable within a section, the section name must be given next to variable name within brackets []. sectionelse is executed when there are no values in the loop variable. Example 7-15. section {* this example will print out all the values of the $custid array *} {section name=customer loop=$custid} id: {$custid[customer]} {/section} OUTPUT: id: 1000 id: 1001 id: 1002 Example 7-16. section loop variable {* the loop variable only determines the number of times to loop. you can access any variable from the template within the section. This example assumes that $custid, $name and $address are all arrays containing the same number of values *} {section name=customer loop=$custid} id: {$custid[customer]} name: {$name[customer]} address: {$address[customer]}
{/section}, Chapter 7. Built-in Functions OUTPUT: id: 1000 name: John Smith address: 253 N 45th
id: 1001 name: Jack Jones address: 417 Mulberry ln
id: 1002 name: Jane Munson address: 5605 apple st
Example 7-17. section names {* the name of the section can be anything you like, and it is used to reference the data within the section *} {section name=mydata loop=$custid} id: {$custid[mydata]} name: {$name[mydata]} address: {$address[mydata]}
{/section} Example 7-18. nested sections {* sections can be nested as deep as you like. With nested sections, you can access complex data structures, such as multi-dimensional arrays. In this example, $contact_type[customer] is an array of contact types for the current customer. *} {section name=customer loop=$custid} id: {$custid[customer]} name: {$name[customer]} address: {$address[customer]} {section name=contact loop=$contact_type[customer]} {$contact_type[customer][contact]}: {$contact_info[customer][contact]} {/section}
{/section} OUTPUT: id: 1000 name: John Smith address: 253 N 45th home phone: 555-555-5555 cell phone: 555-555-5555 e-mail: email is hidden
id: 1001 name: Jack Jones address: 417 Mulberry ln home phone: 555-555-5555 cell phone: 555-555-5555 e-mail: email is hidden
id: 1002 name: Jane Munson address: 5605 apple st , Chapter 7. Built-in Functions home phone: 555-555-5555 cell phone: 555-555-5555 e-mail: email is hidden
Example 7-19. sections and associative arrays {* This is an example of printing an associative array of data within a section *} {section name=customer loop=$contacts} name: {$contacts[customer].name} home: {$contacts[customer].home} cell: {$contacts[customer].cell} e-mail: {$contacts[customer].email}
{/section} OUTPUT: name: John Smith home: 555-555-5555 cell: 555-555-5555 e-mail: email is hidden
name: Jack Jones home phone: 555-555-5555 cell phone: 555-555-5555 e-mail: email is hidden
name: Jane Munson home phone: 555-555-5555 cell phone: 555-555-5555 e-mail: email is hidden
Example 7-20. sectionelse {* sectionelse will execute if there are no $custid values *} {section name=customer loop=$custid} id: {$custid[customer]} {sectionelse} there are no values in $custid. {/section} Sections also have their own variables that handle section properties. These are indi- cated like so: {$smarty.section.sectionname.varname} NOTE: As of Smarty 1.5.0, the syntax for section property variables has been changed from {%sectionname.varname%} to {$smarty.section.sectionname.varname}. The old syntax is still supported, but you will only see reference to the new syntax in the manual examples. index index is used to display the current loop index, starting with zero (or the start at- tribute if given), and incrementing by one (or by the step attribute if given.) Technical Note: If the step and start section properties are not modified, then this works the same as the iteration section property, except it starts on 0 instead of 1., Chapter 7. Built-in Functions Example 7-21. section property index {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]} {/section} OUTPUT: 0 id: 1000 1 id: 1001 2 id: 1002 index_prev index_prev is used to display the previous loop index. on the first loop, this is set to -1. Example 7-22. section property index_prev {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]} {* FYI, $custid[customer.index] and $custid[customer] are identical in mean- ing *} {if $custid[customer.index_prev] ne $custid[customer.index]} The customer id changed {/if} {/section} OUTPUT: 0 id: 1000 The customer id changed 1 id: 1001 The customer id changed 2 id: 1002 The customer id changed index_next index_next is used to display the next loop index. On the last loop, this is still one more than the current index (respecting the setting of the step attribute, if given.) Example 7-23. section property index_next {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]} {* FYI, $custid[customer.index] and $custid[customer] are identical in mean- ing *} {if $custid[customer.index_next] ne $custid[customer.index]} The customer id will change {/if} {/section} OUTPUT: 0 id: 1000 The customer id will change 1 id: 1001 , Chapter 7. Built-in Functions The customer id will change 2 id: 1002 The customer id will change iteration iteration is used to display the current loop iteration. NOTE: This is not affected by the section properties start, step and max, unlike the index property. Iteration also starts with 1 instead of 0 like index. rownum is an alias to iteration, they work identical. Example 7-24. section property iteration {section name=customer loop=$custid start=5 step=2} current loop iteration: {$smarty.section.customer.iteration} {$smarty.section.customer.index} id: {$custid[customer]} {* FYI, $custid[customer.index] and $custid[customer] are identical in mean- ing *} {if $custid[customer.index_next] ne $custid[customer.index]} The customer id will change {/if} {/section} OUTPUT: current loop iteration: 1 5 id: 1000 The customer id will change current loop iteration: 2 7 id: 1001 The customer id will change current loop iteration: 3 9 id: 1002 The customer id will change first first is set to true if the current section iteration is the first one. Example 7-25. section property first {section name=customer loop=$custid} {if $smarty.section.customer.first}
last last is set to true if the current section iteration is the last one. Example 7-26. section property last {section name=customer loop=$custid} {if $smarty.section.customer.first}
rownum rownum is used to display the current loop iteration, starting with one. It is an alias to iteration, they work identically. Example 7-27. section property rownum {section name=customer loop=$custid} {$smarty.section.customer.rownum} id: {$custid[customer]} {/section} OUTPUT: 1 id: 1000 2 id: 1001 3 id: 1002 loop loop is used to display the last index number that this section looped. This can be used inside or after the section., Chapter 7. Built-in Functions Example 7-28. section property index {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]} {/section} There were {$smarty.section.customer.loop} customers shown above. OUTPUT: 0 id: 1000 1 id: 1001 2 id: 1002 There were 3 customers shown above. show show is used as a parameter to section. show is a boolean value, true or false. If false, the section will not be displayed. If there is a sectionelse present, that will be alter- nately displayed. Example 7-29. section attribute show {* $show_customer_info may have been passed from the PHP application, to regulate whether or not this section shows *} {section name=customer loop=$custid show=$show_customer_info} {$smarty.section.customer.rownum} id: {$custid[customer]} {/section} {if $smarty.section.customer.show} the section was shown. {else} the section was not shown. {/if} OUTPUT: 1 id: 1000 2 id: 1001 3 id: 1002 the section was shown. total total is used to display the number of iterations that this section will loop. This can be used inside or after the section. Example 7-30. section property total {section name=customer loop=$custid step=2} {$smarty.section.customer.index} id: {$custid[customer]} {/section} There were {$smarty.section.customer.total} customers shown above. OUTPUT: 0 id: 1000 , Chapter 7. Built-in Functions 2 id: 1001 4 id: 1002 There were 3 customers shown above. strip Many times web designers run into the issue where white space and carriage returns affect the output of the rendered HTML (browser "features"), so you must run all your tags together in the template to get the desired results. This usually ends up in unreadable or unmanageable templates. Anything within {strip}{/strip} tags in Smarty are stripped of the extra spaces or carriage returns at the beginnings and ends of the lines before they are displayed. This way you can keep your templates readable, and not worry about extra white space causing problems. Technical Note: {strip}{/strip} does not affect the contents of template variables. See the strip modifier function. Example 7-31. strip tags {* the following will be all run into one line upon output *} {strip}
Notice that in the above example, all the lines begin and end with HTML tags. Be aware that all the lines are run together. If you have plain text at the beginning or end of any line, they will be run together, and may not be desired results.,
Chapter 8. Custom Functions
Smarty comes with several custom functions that you can use in the templates. assign Attribute Name Type Required Default Description var string Yes n/a The name of the variable being assigned value string Yes n/a The value being assigned assign is used for assigning template variables during the execution of the template. Example 8-1. assign {assign var="name" value="Bob"} The value of $name is {$name}. OUTPUT: The value of $name is Bob. counter Attribute Name Type Required Default Description name string No default The name of the counter start number No 1 The initial number to start counting from skip number No 1 The interval to count by direction string No up the direction to count (up/down) print boolean No true Whether or not to print the value assign string No n/a the template variable the output will be assigned to counter is used to print out a count. counter will remember the count on each itera- tion. You can adjust the number, the interval and the direction of the count, as well as determine whether or not to print the value. You can run multiple counters con- currently by supplying a unique name for each one. If you do not supply a name, the, Chapter 8. Custom Functions name ’default’ will be used. If you supply the special "assign" attribute, the output of the counter function will be assigned to this template variable instead of being output to the template. Example 8-2. counter {* initialize the count *} {counter start=0 skip=2 print=false} {counter} {counter} {counter} {counter} OUTPUT: 2 4 6 8 cycle Attribute Name Type Required Default Description name string No default The name of the cycle values mixed Yes N/A The values to cycle through, either a comma delimited list (see delimiter attribute), or an array of values. print boolean No true Whether to print the value or not advance boolean No true Whether or not to advance to the next value delimiter string No , The delimiter to use in the values attribute. assign string No n/a the template variable the output will be assigned to Cycle is used to cycle though a set of values. This makes it easy to alternate between two or more colors in a table, or cycle through an array of values. You can cycle through more than one set of values in your template by supplying a name attribute. Give each set of values a unique name. You can force the current value not to print with the print attribute set to false. This, Chapter 8. Custom Functions would be useful for silently skipping a value. The advance attribute is used to repeat a value. When set to true, the next call to cycle will print the same value. If you supply the special "assign" attribute, the output of the cycle function will be assigned to this template variable instead of being output to the template. Example 8-3. cycle {section name=rows loop=$data}
{$data[rows]}
{/section} OUTPUT:
1
2
3
debug Attribute Name Type Required Default Description output string No html output type, html or javascript {debug} dumps the debug console to the page. This works regardless of the debug settings in Smarty. Since this gets executed at runtime, this is only able to show the assigned variables, not the templates that are in use. But, you see all the currently available variables within the scope of this template. eval Attribute Name Type Required Default Description var mixed Yes n/a variable (or string) to evaluate assign string No n/a the template variable the output will be assigned to eval is used to evaluate a variable as a template. This can be used for things like embedding template tags/variables into variables or tags/variables into config file variables., Chapter 8. Custom Functions If you supply the special "assign" attribute, the output of the eval function will be assigned to this template variable instead of being output to the template. Technical Note: Evaluated variables are treated the same as templates. They follow the same escapement and security features just as if they were templates. Technical Note: Evaluated variables are compiled on every invocation, the compiled ver- sions are not saved! However if you have caching enabled, the output will be cached with the rest of the template. Example 8-4. eval setup.conf - emphstart = emphend = title = Welcome to {$company}’s home page! ErrorCity = You must supply a {#emphstart#}city{#emphend#}. ErrorState = You must supply a {#emphstart#}state{#emphend#}. index.tpl - {config_load file="setup.conf"} {eval var=$foo} {eval var=#title#} {eval var=#ErrorCity#} {eval var=#ErrorState# assign="state_error"} {$state_error} OUTPUT: This is the contents of foo. Welcome to Foobar Pub & Grill’s home page! You must supply a city. You must supply a state. fetch Attribute Name Type Required Default Description file string Yes n/a the file, http or ftp site to fetch assign string No n/a the template variable the output will be assigned to fetch is used to fetch files from the local file system, http, or ftp and display the con- tents. If the file name begins with "http://", the web site page will be fetched and displayed. If the file name begins with "ftp://", the file will be fetched from the ftp server and displayed. For local files, the full system file path must be given, or a path, Chapter 8. Custom Functions relative to the executed php script. If you supply the special "assign" attribute, the output of the fetch function will be assigned to this template variable instead of being output to the template. (new in Smarty 1.5.0) Technical Note: This will not support http redirects, be sure to include a trailing slash on your web page fetches where necessary. Technical Note: If template security is turned on and you are fetching a file from the local file system, this will only allow files from within one of the defined secure directories. ($secure_dir) Example 8-5. fetch {* include some javascript in your template *} {fetch file="/export/httpd/www.domain.com/docs/navbar.js"} {* embed some weather text in your template from another web site *} {fetch file="http://www.myweather.com/68502/"} {* fetch a news headline file via ftp *} {fetch file="ftp://user:email is hidden/path/to/currentheadlines.txt"} {* assign the fetched contents to a template variable *} {fetch file="http://www.myweather.com/68502/" assign="weather"} {if $weather ne ""} {$weather} {/if} html_checkboxes Attribute Name Type Required Default Description name string No checkbox name of checkbox list values array Yes, unless n/a an array of using options values for attribute checkbox buttons output array Yes, unless n/a an array of using options output for attribute checkbox buttons checked string No empty the checked checkbox element options associative Yes, unless n/a an associative array using values array of values and output and output, Chapter 8. Custom Functions Attribute Name Type Required Default Description separator string No empty string of text to separate each checkbox item html_checkboxes is a custom function that creates an html checkbox group with pro- vided data. It takes care of which item(s) are selected by default as well. Required at- tributes are values and output, unless you use options instead. All output is XHTML compatible. All parameters that are not in the list above are printed as name/value-pairs inside each of the created -tags. Example 8-6. html_checkboxes index.php: require(’Smarty.php.class’); $smarty = new Smarty; $smarty->assign(’cust_ids’, array(1000,1001,1002,1003)); $smarty->assign(’cust_names’, array(’Joe Schmoe’,’Jack Smith’,’Jane Johnson’,’CHarlie Brown’)); $smarty->assign(’customer_id’, 1001); $smarty->display(’index.tpl’); index.tpl: {html_checkboxes values=$cust_ids checked=$customer_id output=$cust_names separator=" "} index.php: require(’Smarty.php.class’); $smarty = new Smarty; $smarty->assign(’cust_checkboxes’, array( 1001 => ’Joe Schmoe’, 1002 => ’Jack Smith’, 1003 => ’Jane Johnson’,’Carlie Brown’)); $smarty->assign(’customer_id’, 1001); $smarty->display(’index.tpl’); index.tpl: {html_checkboxes name="id" checkboxes=$cust_checkboxes checked=$customer_id separator=" "} OUTPUT: (both examples) Joe Schmoe
Smith Micro Software Product Registration Product registration entitles you to future upgrades, expert technical support, special discounts and offers, and product announcements. Register your software online: www.smithmicro.com/register/ Please write legibly and complete the entire card. Fax to (83
5-in-1 Super Mario All-Stars/Super Mario World Nintendo December 1994 7th Saga, The Enix September 1993 A.S.P.: Air Strike Patrol Seta January 1995 Aaahh!!! Real Monsters Majesco November 1995 ABC's Monday Night Football Data East December 1993 ACME Animation Factory Sunsoft November 1994 ActRaiser
- THE ZEITGEIST MOVEMENT - OBSERVATIONS AND RESPONSES Activist Orientation Guide www.thezeitgeistmovement.com | www.thevenusproject.com PREFACE: The Zeitgeist Movement is the activist arm of The Venus Project, which constitutes the life long work of industrial designer and social engineer, Jacque Fr
INTEL SOFTWARE LICENSE AGREEMENT (Alpha, Beta, Prototype Site License) IMPORTANT - READ BEFORE COPYING, INSTALLING OR USING. Do not use or load software from this site or any associated materials (collectively, the "Software") until you have carefully read the following terms and conditions. By load
Software Upgrade Guide < Contents > - Notice - File Copy - USB Download 1. Notice Notice A few USB devices may not be compatible with the TV. If the USB device isn’t compatible, you use another USB device. The USB download works only on the antenna input source (DTV or ATV). It doesn’t work on th
DOE/GO-10096-050 E FS 119NERGY March 1996 EFFICIENCY AND RENEWABLE Solar Water Heating ENERGY This publication provides basic informa- cost of solar water heaters is higher than tion on the components and types of solar that of conventional water heaters, the water heaters currently available and th
CYNIC Kindly Bent to Free Us Release date: February 14th, 2014 – North America February 18th, 2014 (Please review this album in your publications released in February) CYNIC finally return with their long awaited second full length since their 2007 reunion. "Kindly Bent to Free Us" is at the same ti
To register on-line with Sonic Foundry, please follow the steps outlined in the registration wizards upon installation of this product. The registration wizard will appear the first time you use Noise Reduction. Registering your product will provide you with technical support, notification of produc
A Practical Guide to Ecological Modelling A Practical Guide to Ecological Modelling Using R as a Simulation Platform Karline Soetaert and Peter M.J. Herman Netherlands Institute of Ecology, Yerseke, The Netherlands Dr. Karline Soetaert Dr. Peter M.J. Herman Netherlands Institute of Ecology Netherlan
CHILLMIX ZONE PRESENT Catalog #: [CMZ010] ********************************* Artist: SPACEBIRDS Title: COSMIC AMBIENCE MIX 001 ********************************* Recorded and Mixed at White Art Studio, 2010 Music created, arrangement, produced and mixed by Spacebirds and EugeneKha 2010(c)Spacebirds Co
THE BRAINWASHING MANUAL 1 The Brainwashing Manual By L. Ron Hubbard Get any book for free on: www.Abika.com THE BRAINWASHING MANUAL 2 BRAIN-WASHING Synthesis of the Russian Textbook on Psychopolitics PSYCHOPOLITICS - the art and science of asserting and maintain- ing dominion over the thoughts and l
A318 SPECIFICATIONS Overall length 31.45 m. 103 ft. 2 in. Height 12.56 m. 41 ft. 2 in. Cabin length 21.38 m. 70 ft. 2 in. Wheelbase 10.25 m. 33 ft. 8 in. two CFM56-5 or two CFM56-5 or Engines PW 6000A PW 6000A Engine thrust range 96-106 kN 22,000-24,000 lb. slst Typical passenger seating 107 107 Ran
Spectralissime High Definition Frequency Analyzer For Any Acoustic Measures. USER MANUAL OFFICIAL WEBSITE www.spectralissime.com VB-AUDIO Spetralissime Non Contractual document page 1 INSTALLATION: Run setup program and follow instructions. Fair Trade, Affordable For Everyone Spectralissime is dist
After the Sound Forge software is installed and you start it for the first time, the registration wizard appears. This wizard offers easy steps that allow you to register the software online with Sony Pictures Digital Inc. Alternatively, you may register online at www.sony.com/mediasoftware at any t
AN10406 Rev. 03 — 3 January 2007 Application note Document information Info Content Keywords Secure Digital (SD), MultiMediaCard (MMC), SPI, Microcontroller, MCU Abstract This document describes how to use the LPC2000 SPI interface to access SD/MMC card Revision history Rev Date Description 03 20070
PAGE 24 PAGE 1 disc one Staring into the black, it’s all I see Holed up in this shroud of obscurity Inhabiting nothing or it’s inhabiting me It’s the ultimate anonymity I set it in motion, I set it right I said what I said then I said goodnight Now my clock’s set forward and I can’t set it back And
This table lists all of the software and firmware on this HP Service Pack for ProLiant. For more information on this deliverable, go to www.hp.com/go/spp/download. Since this is the initial version of the HP Service Pack for ProLiant, if the text is Blue, then the component version has been updated
BIOS - System ROM Online ROM Flash Component for Linux - HP ProLiant BL260c G5 (I20) Servers, v2010.10.25 P Online ROM Flash Component for Linux - HP ProLiant BL280c G6 (I22) Servers, v2011.05.05 P Online ROM Flash Component for Linux - HP ProLiant BL2x220c G5 (I19) Servers, v2010.10.25 P Online ROM
D.2.j (Database Talk) [SQL Roles: Users and Security in InterBase] SQL Roles: Users and Security in InterBase Brett Bandy Markus Kemper BorCon 1998 Databases need security. Data stored in database files must be secure. InterBase provides two levels of security for data; user validation and database
SAP Excellence Series Editors: Professor Dr. Dr. h.c. mult. Peter Mertens Universität Erlangen-Nürnberg Dr. Peter Zencke SAP AG, Walldorf Jörg Thomas Dickersbach Characteristic Based Planning with mySAP SCM™ Scenarios, Processes, and Functions With contributions by A. Forstreuter, C. Fuhlbrügge and
sysshock man -eng 02/05/2000 9:11 Page 1 SYSTEM SHOCK 2® WARNING: TO OWNERS OF PROJECTION TELEVISIONS STILL PICTURES OR IMAGES MAY CAUSE PERMANENT PICTURE-TUBE DAMAGE OR MARK THE PHOSPHOR OF THE CRT. AVOID REPEATED OR EXTENDED USE OF VIDEO GAMES ON LARGE- SCREEN PROJECTION TELEVISIONS. EPILEPSY WARN
STEERING SYSTEM SECTIONST CONTENTS PRECAUTIONS ...2 TILT MECHANISM ...15 Supplemental Restraint System (SRS) ″AIR POWER STEERING GEAR AND LINKAGE ...16 BAG″ and ″SEAT BELT PRE-TENSIONER″...2 Components...16 Precautions for Steering System...2 Removal and Installation ...17 PREPARATION ...3 Disassemb
g GETTING STARTEDDPCSystem Requirements Computer: Pentium 90 MHz processor or equivalent. Operating Systems: Windows 2000, Windows XP, or Windows Vista. Memory: 16 MB of RAM Controls: A keyboard and mouse are required. Joysticks, game pads, graphic tablets, and input devices other than the mouse and
S2 Map.qxp 3/3/97 11:33 AM Page1agad300ItIlluminatil Mensaez g wr ep Orz gg etabth etbbdzLalande epep a Bootis zaad250 et g Vulpeculaed g bSaurusdgbbaagaProcyon Olber Rigel Mira 200 Zeeman a bd g ep Wolf g Vela bbbzaaRaynet a Luyten et b Sirius a 150 VolantisbgCanopus IndiSolbaMizardaPk gu Lyrae Reg
EPILEPSY WARNING Please read before using this video game system or allowing your children to use it. Some people are susceptible to epileptic seizures or loss of consciousness when exposed to certain flashing lights or light patterns in every day life. Such people may have a seizure while watching
Designer COMING SOON! o( DEBRA B AILEY )o Here's more Star Wars reading that you won't want to miss! Assistant Editor STAR WARS: EMPIRE #2J by JEREMY BARLOW and BRANDON BADEAUX o( KATIE MOODY )o Cover by KILIAN PLUNKETT It was supposed to be an easy gig ... transport a young woman across the desert