diff --git a/docs/appendixes.sgml b/docs/appendixes.sgml new file mode 100644 index 00000000..7b00e877 --- /dev/null +++ b/docs/appendixes.sgml @@ -0,0 +1,411 @@ + + Appendixes + + Troubleshooting + + + Smarty/PHP errors + + Smarty can catch many errors such as missing tag attributes + or malformed variable names. If this happens, you will see an error + similar to the following: + + + +Smarty errors + +Warning: Smarty: [in index.tpl line 4]: syntax error: unknown tag - '%blah' + in /path/to/smarty/Smarty.class.php on line 1041 + +Fatal error: Smarty: [in index.tpl line 28]: syntax error: missing section name + in /path/to/smarty/Smarty.class.php on line 1041 + + + + Smarty shows you the template name, the line number and the error. + After that, the error consists of the actual line number in the Smarty + class that the error occured. + + + + There are certain errors that Smarty cannot catch, such as missing + close tags. These types of errors usually end up in PHP compile-time + parsing errors. + + + +PHP parsing errors + +Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75 + + + + When you encounter a PHP parsing error, the error line number will + correspond to the compiled PHP script, not the template itself. Usually + you can look at the template and spot the syntax error. Here are some + common things to look for: missing close tags for {if}{/if} or + {section}{/section}, or syntax of logic within an {if} tag. If you + can't find the error, you might have to open the compiled PHP file and + go to the line number to figure out where the corresponding error is in + the template. + + + + + Tips & Tricks + + + + Blank Variable Handling + + There may be times when you want to print a default value for an empty + variable instead of printing nothing, such as printing "&nbsp;" so that + table backgrounds work properly. Many would use an {if} statement to + handle this, but there is a shorthand way with Smarty, using the + default variable modifier. + + +Printing &nbsp; when a variable is empty + + +{* the long way *} + +{if $title eq ""} + &nbsp; +{else} + {$title} +{/if} + + +{* the short way *} + +{$title|default:"&nbsp;"} + + + + Default Variable Handling + + If a variable is used frequently throughout your templates, applying + the default modifier every time it is mentioned can get a bit ugly. You + can remedy this by assigning the variable its default value with the + assign function. + + +Assigning a template variable its default value + +{* do this somewhere at the top of your template *} +{assign var="title" value=$title|default:"no title"} + +{* if $title was empty, it now contains the value "no title" when you print it *} +{$title} + + + + Passing variable title to header template + + When the majority of your templates use the same headers and footers, it + is common to split those out into their own templates and include them. + But what if the header needs to have a different title, depending on + what page you are coming from? You can pass the title to the header when + it is included. + + +Passing the title variable to the header template + + +mainpage.tpl +------------ + +{include file="header.tpl" title="Main Page"} +{* template body goes here *} +{include file="footer.tpl"} + + +archives.tpl +------------ + +{config_load file="archive_page.conf"} +{include file="header.tpl" title=#archivePageTitle#} +{* template body goes here *} +{include file="footer.tpl"} + + +header.tpl +---------- +<HTML> +<HEAD> +<TITLE>{$title|default:"BC News"}</TITLE> +</HEAD> +<BODY> + + +footer.tpl +---------- +</BODY> +</HTML> + + + When the main page is drawn, the title of "Main Page" is passed to the + header.tpl, and will subsequently be used as the title. When the + archives page is drawn, the title will be "Archives". Notice in the + archive example, we are using a variable from the archives_page.conf + file instead of a hard coded variable. Also notice that "BC News" is + printed if the $title variable is not set, using the + default variable modifier. + + + + Dates + + As a rule of thumb, always pass dates to Smarty as timestamps. + This allows template designers to use date_format for full control over date + formatting, and also makes it easy to compare dates if necessary. + + + NOTE: As of Smarty 1.4.0, you can pass dates to Smarty as unix + timestamps, mysql timestamps, or any date parsable by strtotime(). + + +using date_format + +{$startDate|date_format} + +OUTPUT: + +Jan 4, 2001 + + +{$startDate|date_format:"%Y/%m/%d"} + +OUTPUT: + +2001/01/04 + + +{if $date1 < $date2} + ... +{/if} + + + When using {html_select_date} in a template, The programmer will most + likely want to convert the output from the form back into timestamp + format. Here is a function to help you with that. + + +converting form date elements back to a timestamp + +// this assumes your form elements are named +// startDate_Day, startDate_Month, startDate_Year + +$startDate = makeTimeStamp($startDate_Year,$startDate_Month,$startDate_Day); + +function makeTimeStamp($year="",$month="",$day="") +{ + if(empty($year)) + $year = strftime("%Y"); + if(empty($month)) + $month = strftime("%m"); + if(empty($day)) + $day = strftime("%d"); + + return mktime(0,0,0,$month,$day,$year); +} + + + + WAP/WML + + WAP/WML templates require a php Content-Type header to be passed along + with the template. The easist way to do this would be to write a custom + function that prints the header. If you are using caching, that won't + work so we'll do it using the insert tag (remember insert tags are not + cached!) Be sure that there is nothing output to the browser before the + template, or else the header may fail. + + +using insert to write a WML Content-Type header + +// be sure apache is configure for the .wml extensions! +// put this function somewhere in your application, or in Smarty.addons.php +function insert_header() { + // this function expects $content argument + extract(func_get_arg(0)); + if(empty($content)) + return; + header($content); + return; +} + +// your Smarty template _must_ begin with the insert tag example: + +{insert name=header content="Content-Type: text/vnd.wap.wml"} + +<?xml version="1.0"?> +<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml"> + +<!-- begin new wml deck --> +<wml> +<!-- begin first card --> +<card> +<do type="accept"> +<go href="#two"/> +</do> +<p> +Welcome to WAP with Smarty! +Press OK to continue... +</p> +</card> +<!-- begin second card --> +<card id="two"> +<p> +Pretty easy isn't it? +</p> +</card> +</wml> + + + + Componentized Templates + + This tip is a bit of a hack, but still a neat idea. Use at your own + risk. ;-) + + + Traditionally, programming templates into your applications goes as + follows: First, you accumulate your variables within your PHP + application, (maybe with database queries.) Then, you instantiate your + Smarty object, assign the variables and display the template. So lets + say for example we have a stock ticker on our template. We would + collect the stock data in our application, then assign these variables + in the template and display it. Now wouldn't it be nice if you could + add this stock ticker to any application by merely including the + template, and not worry about fetching the data up front? + + + You can embed PHP into your templates with the {php}{/php} tags. + With this, you can setup self contained templates with their own + data structures for assigning their own variables. With the logic + embedded like this, you can keep the template & logic together. This + way no matter where the template source is coming from, it is always + together as one component. + + +componentized template + +{* Smarty *} + +{php} + + // setup our function for fetching stock data + function fetch_ticker($symbol,&$ticker_name,&$ticker_price) { + // put logic here that fetches $ticker_name + // and $ticker_price from some resource + } + + // call the function + fetch_ticker("YHOO",$ticker_name,$ticker_price); + + // assign template variables + $this->assign("ticker_name",$ticker_name); + $this->assign("ticker_price",$ticker_price); + +{/php} + +Stock Name: {$ticker_name} Stock Price: {$ticker_price} + + + As of Smarty 1.5.0, there is even a cleaner way. You can include php in + your templates with the {include_php ...} tag. This way you can keep + your PHP logic separated from the template logic. See the include_php function for + more information. + + +componentized template with include_php + +load_ticker.php +--------------- + +<?php + // setup our function for fetching stock data + function fetch_ticker($symbol,&$ticker_name,&$ticker_price) { + // put logic here that fetches $ticker_name + // and $ticker_price from some resource + } + + // call the function + fetch_ticker("YHOO",$ticker_name,$ticker_price); + + // assign template variables + $this->assign("ticker_name",$ticker_name); + $this->assign("ticker_price",$ticker_price); +?> + + +index.tpl +--------- + +{* Smarty *} + +{include_php file="load_ticker.php"} + +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 + lists? One way spammers collect E-mail addresses is from web pages. To + help combat this problem, you can make your E-mail address show up in a + scrambled looking form in the HTML source, yet it it will look and work + correctly in the browser. This is done with the escape modifier. + + +Example of Obfuscating an E-mail Address + + +index.tpl +--------- + +Send inquiries to +<a href="mailto:{$EmailAddress|escape:"hex"}>{$EmailAddress|escape:"hexentity"}</a> + +OUTPUT: + +Send inquiries to +<a +href="mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&#x40;&#x6d;&#x65;&#x2e;&#x6e;&#x65;&#x74;</a> + + + + + Although this looks like a mess in the HTML source, it will render + correctly in your browser, and the mailto: hyperlink will go to the correct + address. + + + TECHNICAL NOTE: This method isn't 100% foolproof. Although highly unlikely, + a spammer could conceivably write his e-mail collecter to decode these + values. + + + + + Resources + + Smarty's homepage is located at http://www.phpinsider.com/php/code/Smarty/. + You can join the mailing list by sending an e-mail to + subscribe-smarty@lists.ispi.net. An archive of the mailing list can be + viewed at http://marc.theaimsgroup.com/?l=smarty&r=1&w=2 + + + + BUGS + + Check the BUGS file that comes with the latest distribution of Smarty, or + check the website. + + + diff --git a/docs/common.dsl b/docs/common.dsl new file mode 100644 index 00000000..ad47f956 --- /dev/null +++ b/docs/common.dsl @@ -0,0 +1,46 @@ +;; -*- Scheme -*- +;; +;; $Id$ +;; +;; This file contains stylesheet customization common to the HTML +;; and print versions. +;; + +;; Stylesheets Localization +(define %default-language% "en") + +(define %use-id-as-filename% #t) +(define %gentext-nav-tblwidth% "100%") +(define %refentry-function% #t) +(define %refentry-generate-name% #f) +(define %funcsynopsis-style% 'ansi) +(define ($legalnotice-link-file$ legalnotice) + (string-append "copyright" %html-ext%)) +(define %generate-legalnotice-link% #t) +(define %footnotes-at-end% #t) +(define %force-chapter-toc% #t) +(define newline "\U-000D") +(define %number-programlisting-lines% #f) +(define %linenumber-mod% 1) +(define %shade-verbatim% #t) + +(define ($generate-book-lot-list$) + ;; REFENTRY generate-book-lot-list + ;; PURP Which Lists of Titles should be produced for Books? + ;; DESC + ;; This parameter should be a list (possibly empty) of the elements + ;; for which Lists of Titles should be produced for each 'Book'. + ;; + ;; It is meaningless to put elements that do not have titles in this + ;; list. If elements with optional titles are placed in this list, only + ;; the instances of those elements that do have titles will appear in + ;; the LOT. + ;; + ;; /DESC + ;; AUTHOR N/A + ;; /REFENTRY + (list (normalize "table"))) + +(define (php-code code) + (make processing-instruction + data: (string-append "php " code "?"))) diff --git a/docs/designers.sgml b/docs/designers.sgml new file mode 100644 index 00000000..e939b52b --- /dev/null +++ b/docs/designers.sgml @@ -0,0 +1,4054 @@ + + Smarty For Template Designers + + Template Language + + The templates are the heart of Smarty. These are the files that the designers + work with. They're basically pages made up of static content interspersed with + template markup tags. These tags are placeholders for variables or blocks of logic. + + + + Basic Syntax + + For these examples, we will assume that you are using the default + template tag delimiters, which are "{" and "}". In Smarty, all content + outside of delimiter tags is displayed as static content, or unchanged. + When Smarty encounters template tags {}, it attempts to interpret what is + between the tags, and displays the appropriate output in place of them. + + + + Comments + + Template comments are surrounded by asterisks, and that is surrounded + by the delimiter tags like so: {* this is a comment *} + Smarty comments are not displayed in the final output of the template. + They are used mainly for making the templates more understandable. + + + Comments + +{* Smarty *} + +{* include the header file here *} +{include file="header.tpl"} + +{include file=$includeFile} + +{include file=#includeFile#} + +{* display dropdown lists *} +<SELECT name=company> +{html_options values=$vals selected=$selected output=$output} +</SELECT> + + + + Attributes + + Attributes to functions are much like HTML attributes. Static + values don't have to be enclosed in quotes, but it is recommended + for literal strings. If not quoted, you may use a syntax that Smarty may confuse + with another function, such as a boolean value. Variables may + also be used, and should not be in quotes. + + +function attribute syntax + +{include file="header.tpl"} + +{include file=$includeFile} + +{include file=#includeFile#} + +<SELECT name=company> +{html_options values=$vals selected=$selected output=$output} +</SELECT> + + + + blah + + Functions are processed and displayed by enclosing the function and its + attributes into delimiters like so: {funcname attr1="val" attr2="val"} + + + function syntax + +{config_load file="colors.conf"} + +{include file="header.tpl"} + +{if $name eq "Fred"} + You are not allowed here +{else} + Welcome, <font color="{#fontColor#}">{$name}!</font> +{/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 located in the Smarty.addons.class + file. They can be modified to your liking, or add new ones. + {html_options} and {html_select_date} are examples of custom + functions. + + + Custom functions in Smarty work much the same as the built-in functions, + except that built-in functions cannot be modified. Custom functions are + located in Smarty.addons.php, built-in functions are not. + + + + + + Variables + + + Variables assigned from PHP + + Variables that are assigned from PHP are referenced by preceding + them with a dollar sign ($) and enclosing the variable in delimiters + like so: $varname + + + + displaying assigned variables + +Hello {$firstname}, glad to see you could make it. +<p> +Your last login was on {$lastLoginDate}. + +OUTPUT: + +Hello Doug, glad to see you could make it. +<p> +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. + + +displaying assigned associative array variables + +{$Contacts.fax}<br> +{$Contacts.email}<br> +{* you can print arrays of arrays as well *} +{$Contacts.phone.home}<br> +{$Contacts.phone.cell}<br> + +OUTPUT: + +555-222-9876<br> +zaphod@slartibartfast.com<br> +555-444-3333<br> +555-111-1234<br> + + + + + Array indexes + + You can reference arrays by their index, much like native PHP + syntax. + + +displaying arrays by index + +{$Contacts[0]}<br> +{$Contacts[1]}<br> +{* you can print arrays of arrays as well *} +{$Contacts[0][0]}<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 + +name: {$person->name}<br> +email: {$person->email}<br> + +OUTPUT: + +name: Zaphod Beeblebrox<br> +email: zaphod@slartibartfast.com<br> + + + + + Variables passed 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#} + + + + +displaying config variables + +<html> +<title>{#pageTitle#}</title> +<body bgcolor="{#bodyBgColor#}"> +<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}"> +<tr bgcolor="{#rowBgColor#}"> + <td>First</td> + <td>Last</td> + <td>Address</td> +</tr> +</table> +</body> +</html> + + + Config file variables cannot be displayed until + after they are loaded in from a config file. This procedure is + explained later in this document under + 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: + + + +displaying request variables + +{* display the variable "page" given in the URL, or from a form using the GET method *} +{$smarty.get.page} + +{* display the variable "page" from a form using the POST method *} +{$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} + + + + + Current timestamp + + 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. + + + +using {$smarty.now} + +{* use the date_format modifier to show current date and time *} +{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} + + + + + Output capture buffer + + The output captured via {capture}..{/capture} construct can be + accessed using {$smarty} variable. See section on + capture for an example. + + + + + Loop properties + + {$smarty} variable can be used to refer to 'section' and + 'foreach' loop properties. See docs for + section and + 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.) + + + Available Modifiers + + capitalize + + This is used to capitalize the first letter of all words in a variable. + + +capitalize + +{$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. + + +count_characters + + +{$articleTitle} +{$articleTitle|count_characters} + +OUTPUT: + +Cold Wave Linked to Temperatures +32 + + + + count_paragraphs + + This is used to count the number of paragraphs in a variable. + + +count_paragraphs + + +{$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. +2 + + + + count_sentences + + This is used to count the number of sentences in a variable. + + +count_sentences + + +{$articleTitle} +{$articleTitle|count_sentences} + +OUTPUT: + +Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe. +2 + + + + count_words + + This is used to count the number of words in a variable. + + +count_words + + +{$articleTitle} +{$articleTitle|count_words} + +OUTPUT: + +Dealers Will Hear Car Talk at Noon. +7 + + + + date_format + + + + + + + + + + Parameter Position + Type + Required + Default + Description + + + + + 1 + string + No + %b %e, %Y + This is the format for the outputted date. + + + + + + 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. + + +date_format + +{$currentDate} +{$currentDate|date_format:"%A, %B %e, %Y"} +{$currentDate|date_format:"%H:%M:%S"} + +OUTPUT: + +Feb 6, 2001 +Tuesday, February 6, 2001 +14:33:00 + + +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 integer, range 00 to 99) + +%d - day of the month as a decimal number (range 00 to 31) + +%D - same as %m/%d/%y + +%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 preceeded 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 corresponding 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 Sunday as the first day of the first week + +%V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 +is the first week that has at least 4 days in the current year, and with Monday 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 Monday 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 + + +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 Position + Type + Required + Default + Description + + + + + 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. + + +default + +{* this will display "no title" (without the quotes) if $articleTitle is empty *} +{$articleTitle|default:"no title"} + +OUTPUT: + +no title + + + + escape + + + + + + + + + + Parameter Position + Type + Required + Possible Values + Default + Description + + + + + 1 + string + No + html,url,quotes,hex,hexentity + html + This is the escape format to use. + + + + + + This is used to html escape, url escape, escape single quotes on a + variable not already escaped, hex escape or hexentity escape. hex + and hexentity escape can be used in conjunction to hide "mailto:" + links on a page from web spiders (spam collectors) and yet keep + them readable and linkable. By default, the variable is html + escaped. + + +escape + +{$articleTitle} +{$articleTitle|escape} +{$articleTitle|escape:"html"} +{$articleTitle|escape:"url"} +{$articleTitle|escape:"quotes"} +<a +href="mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}</a> + +OUTPUT: + +'Stiff Opposition Expected to Casketless Funeral Plan' +'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\' +<a +href="mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&#x40;&#x6d;&#x65;&#x2e;&#x6e;&#x65;&#x74;</a> + + + + indent + + + + + + + + + + Parameter Position + Type + Required + Default + Description + + + + + 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.) + + +indent + +{$articleTitle} + +{$articleTitle|indent} + +{$articleTitle|indent:10} + +{$articleTitle|indent:1:"\t"} + +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 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. + + + + lower + + This is used to lowercase a variable. + + +lower + +{$articleTitle} +{$articleTitle|lower} + +OUTPUT: + +Two Convicts Evade Noose, Jury Hung. +two convicts evade noose, jury hung. + + + + regex_replace + + + + + + + + + + Parameter Position + Type + Required + Default + Description + + + + + 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. + + + NOTE: This function was added to Smarty 1.4.3. + + +regex_replace + +{* 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 Position + Type + Required + Default + Description + + + + + 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. + + +replace + +{$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 Position + Type + Required + Default + Description + + + + + 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. + + +spacify + +{$articleTitle} +{$articleTitle|spacify} +{$articleTitle|spacify:"^^"} + +OUTPUT: + +Something Went Wrong in Jet Crash, Experts Say. +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 . +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 + + + + + + + + + + Parameter Position + Type + Required + Default + Description + + + + + 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. + + +string_format + +{$number} +{$number|string_format:"%.2f"} +{$number|string_format:"%d"} + +OUTPUT: + +23.5787446 +23.58 +24 + + + + strip_tags + + This strips out markup tags, basically anything between < and >. + + +strip_tags + +{$articleTitle} +{$articleTitle|strip_tags} + +OUTPUT: + +Blind Woman Gets <font face="helvetica">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>. +Blind Woman Gets New Kidney from Dad she Hasn't Seen in years. + + + + truncate + + + + + + + + + + Parameter Position + Type + Required + Default + Description + + + + + 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 parameter, you can specify a string of text + to display at the end if the variable was truncated. 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. + + +truncate + +{$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. + + +upper + +{$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 Position + Type + Required + Default + Description + + + + + 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. + + + 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. + + +wordwrap + +{$articleTitle} + +{$articleTitle|wordwrap:30} + +{$articleTitle|wordwrap:20} + +{$articleTitle|wordwrap:30:"<br>\n"} + +{$articleTitle|wordwrap:30:"\n":false} + +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<br> +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 + +{$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. +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 F F I C I E N C Y . +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 + + 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 displaying 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. capture + was added to Smarty 1.4.0. The "name" attribute was added to Smarty + 1.4.5. + + + 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. + + + + 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. + + + + + 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 ""} + <tr> + <td> + {$return} + </td> + </tr> +{/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 + + + 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. NOTE: This was added to Smarty 1.4.3. + + + + 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 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. + + +function config_load + + +{config_load file="colors.conf"} + +<html> +<title>{#pageTitle#}</title> +<body bgcolor="{#bodyBgColor#}"> +<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}"> + <tr bgcolor="{#rowBgColor#}"> + <td>First</td> + <td>Last</td> + <td>Address</td> + </tr> +</table> +</body> +</html> + + + 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 nothing + to do with each other, they just happen to share a common naming + convention. + + +function config_load with section + +{config_load file="colors.conf" section="Customer"} + +<html> +<title>{#pageTitle#}</title> +<body bgcolor="{#bodyBgColor#}"> +<table border="{#tableBorderSize#}" bgcolor="{#tableBgColor#}"> + <tr bgcolor="{#rowBgColor#}"> + <td>First</td> + <td>Last</td> + <td>Address</td> + </tr> +</table> +</body> +</html> + + + + 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 variables available in the current template are also + available within the included template. The include tag must have + the attribute "file", which contains the template resource path. + + + You an optionally pass the assign attribute, + which will specify a template variable name that the output of + include will be assigned to instead of + displayed. This was added to Smarty 1.5.0. + + +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 explicitly 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. + + +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. + + +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 + + + 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 enabled, 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. + + + You an optionally pass the assign attribute, + which will specify a template variable name that the output of + include will be assigned to instead of + displayed. + + + include_php was added to Smarty 1.5.0. + + +function include_php + +load_nav.php +------------- + +<?php + + // load in variables from a mysql db and assign them to the template + require_once("MySQL.class.php"); + $sql = new MySQL; + $sql->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} + <a href="{$curr_section.url}">{$curr_section.name}</a><br> +{/foreach} + + + + insert + + + + + + + + + + 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. + + +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: assiging the output to a template variable + isn't too useful with caching enabled. (added to Smarty 1.5.0) + + + 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. (added to Smarty + 1.5.2) + + + 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. (added in 1.4.5) + + + 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 surrounding elements by + spaces. + + +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} + +{* 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. + + +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. + + +literal tags + +{literal} + <script language=javascript> + + <!-- + function isblank(field) { + if (field.value == '') + { return false; } + else + { + document.loginform.submit(); + return true; + } + } + // --> + + </script> +{/literal} + + + + php + + php tags allow php to be embedded directly into the template. They + will not be escaped, regardless of the $php_handling setting. This + is for advanced users only, not normally needed. This was added to + 1.4.0. + + +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 + [$variable_name] + Yes + n/a + The name of the 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. (Added to Smarty 1.4.4.) + + + 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. (Added to Smarty 1.4.4.) + + + max + integer + No + 1 + Sets the maximum number of times the section + will loop. (Added to Smarty 1.4.4.) + + + 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. Sections 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. + + +section + + +{* this example will print out all the values of the $custid array *} +{section name=customer loop=$custid} + id: {$custid[customer]}<br> +{/section} + +OUTPUT: + +id: 1000<br> +id: 1001<br> +id: 1002<br> + + + +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]}<br> + name: {$name[customer]}<br> + address: {$address[customer]}<br> + <p> +{/section} + + +OUTPUT: + +id: 1000<br> +name: John Smith<br> +address: 253 N 45th<br> +<p> +id: 1001<br> +name: Jack Jones<br> +address: 417 Mulberry ln<br> +<p> +id: 1002<br> +name: Jane Munson<br> +address: 5605 apple st<br> +<p> + + + +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]}<br> + name: {$name[mydata]}<br> + address: {$address[mydata]}<br> + <p> +{/section} + + + +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]}<br> + name: {$name[customer]}<br> + address: {$address[customer]}<br> + {section name=contact loop=$contact_type[customer]} + {$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br> + {/section} + <p> +{/section} + + +OUTPUT: + +id: 1000<br> +name: John Smith<br> +address: 253 N 45th<br> +home phone: 555-555-5555<br> +cell phone: 555-555-5555<br> +e-mail: john@mydomain.com<br> +<p> +id: 1001<br> +name: Jack Jones<br> +address: 417 Mulberry ln<br> +home phone: 555-555-5555<br> +cell phone: 555-555-5555<br> +e-mail: jack@mydomain.com<br> +<p> +id: 1002<br> +name: Jane Munson<br> +address: 5605 apple st<br> +home phone: 555-555-5555<br> +cell phone: 555-555-5555<br> +e-mail: jane@mydomain.com<br> +<p> + + + +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}<br> + home: {$contacts[customer].home}<br> + cell: {$contacts[customer].cell}<br> + e-mail: {$contacts[customer].email}<p> +{/section} + + +OUTPUT: + +name: John Smith<br> +home: 555-555-5555<br> +cell: 555-555-5555<br> +e-mail: john@mydomain.com<p> +name: Jack Jones<br> +home phone: 555-555-5555<br> +cell phone: 555-555-5555<br> +e-mail: jack@mydomain.com<p> +name: Jane Munson<br> +home phone: 555-555-5555<br> +cell phone: 555-555-5555<br> +e-mail: jane@mydomain.com<p> + + + + + +sectionelse + +{* sectionelse will execute if there are no $custid values *} +{section name=customer loop=$custid} + id: {$custid[customer]}<br> +{sectionelse} + there are no values in $custid. +{/section} + + + Sections also have their own variables that handle section properties. + These are indicated 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 attribute 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. + + + section property index + + {section name=customer loop=$custid} + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {/section} + + + OUTPUT: + + 0 id: 1000<br> + 1 id: 1001<br> + 2 id: 1002<br> + + + + + index_prev + + index_prev is used to display the previous loop index. + on the first loop, this is set to -1. + + + section property index_prev + + {section name=customer loop=$custid} + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *} + {if $custid[customer.index_prev] ne $custid[customer.index]} + The customer id changed<br> + {/if} + {/section} + + + OUTPUT: + + 0 id: 1000<br> + The customer id changed<br> + 1 id: 1001<br> + The customer id changed<br> + 2 id: 1002<br> + The customer id changed<br> + + + + + 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.) + + + section property index_next + + {section name=customer loop=$custid} + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *} + {if $custid[customer.index_next] ne $custid[customer.index]} + The customer id will change<br> + {/if} + {/section} + + + OUTPUT: + + 0 id: 1000<br> + The customer id will change<br> + 1 id: 1001<br> + The customer id will change<br> + 2 id: 1002<br> + The customer id will change<br> + + + + + 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. + + + This was added to Smarty 1.4.4. + + + section property iteration + + {section name=customer loop=$custid start=5 step=2} + current loop iteration: {$smarty.section.customer.iteration}<br> + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {* FYI, $custid[customer.index] and $custid[customer] are identical in meaning *} + {if $custid[customer.index_next] ne $custid[customer.index]} + The customer id will change<br> + {/if} + {/section} + + + OUTPUT: + + current loop iteration: 1 + 5 id: 1000<br> + The customer id will change<br> + current loop iteration: 2 + 7 id: 1001<br> + The customer id will change<br> + current loop iteration: 3 + 9 id: 1002<br> + The customer id will change<br> + + + + + first + + first is set to true if the current section iteration is the first + one. + + + section property first + + {section name=customer loop=$custid} + {if $smarty.section.customer.first} + <table> + {/if} + + <tr><td>{$smarty.section.customer.index} id: + {$custid[customer]}</td></tr> + + {if $smarty.section.customer.last} + </table> + {/if} + {/section} + + + OUTPUT: + + <table> + <tr><td>0 id: 1000</td></tr> + <tr><td>1 id: 1001</td></tr> + <tr><td>2 id: 1002</td></tr> + </table> + + + + + last + + last is set to true if the current section iteration is the last + one. + + + section property last + + {section name=customer loop=$custid} + {if $smarty.section.customer.first} + <table> + {/if} + + <tr><td>{$smarty.section.customer.index} id: + {$custid[customer]}</td></tr> + + {if $smarty.section.customer.last} + </table> + {/if} + {/section} + + + OUTPUT: + + <table> + <tr><td>0 id: 1000</td></tr> + <tr><td>1 id: 1001</td></tr> + <tr><td>2 id: 1002</td></tr> + </table> + + + + + rownum + + rownum is used to display the current loop iteration, + starting with one. + + + section property rownum + + {section name=customer loop=$custid} + {$smarty.section.customer.rownum} id: {$custid[customer]}<br> + {/section} + + + OUTPUT: + + 1 id: 1000<br> + 2 id: 1001<br> + 3 id: 1002<br> + + + + + loop + + loop is used to display the last index number that this section + looped. This can be used inside or after the section. + + + section property index + + {section name=customer loop=$custid} + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {/section} + + There were {$smarty.section.customer.loop} customers shown above. + + OUTPUT: + + 0 id: 1000<br> + 1 id: 1001<br> + 2 id: 1002<br> + + 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 alternately displayed. + + + 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]}<br> + {/section} + + {if $smarty.section.customer.show} + the section was shown. + {else} + the section was not shown. + {/if} + + + OUTPUT: + + 1 id: 1000<br> + 2 id: 1001<br> + 3 id: 1002<br> + + 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. + + + This was added to Smarty 1.4.4. + + + section property total + + {section name=customer loop=$custid step=2} + {$smarty.section.customer.index} id: {$custid[customer]}<br> + {/section} + + There were {$smarty.section.customer.total} customers shown above. + + OUTPUT: + + 0 id: 1000<br> + 2 id: 1001<br> + 4 id: 1002<br> + + There were 3 customers shown above. + + + + + + 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 anything 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 variable (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. + + +foreach + + +{* this example will print out all the values of the $custid array *} +{foreach from=$custid item=curr_id} + id: {$curr_id}<br> +{/foreach} + +OUTPUT: + +id: 1000<br> +id: 1001<br> +id: 1002<br> + + + +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}<br> + {/foreach} +{/foreach} + +OUTPUT: + +phone: 1<br> +fax: 2<br> +cell: 3<br> +phone: 555-4444<br> +fax: 555-3333<br> +cell: 760-1234<br> + + + + 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 + unmanagable 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. + + +strip tags + +{* the following will be all run into one line upon output *} +{strip} +<table border=0> + <tr> + <td> + <A HREF="{$url}"> + <font color="red">This is a test</font> + </A> + </td> + </tr> +</table> +{/strip} + + +OUTPUT: + +<table border=0><tr><td><A HREF="http://my.domain.com"><font color="red">This is a test</font></A></td></tr></table> + + + 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. + + + + + + Additional Functions + + Smarty comes with several additional functions that you can + use in the templates. + + + + Available Functions + + 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. + + + NOTE: This was added to Smarty 1.4.3. + + +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 + + + + + id + string + No + default + The id 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 iteration. 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 concurrently by + supplying a unique id for each one. If you do not supply an id, the + default id will be used. counter was added to Smarty 1.4.0. + + + 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. (new in Smarty 1.5.0) + + +counter + +{* initialize the count *} +{counter start=0 skip=2 print=false} + +{counter}<br> +{counter}<br> +{counter}<br> +{counter}<br> + +OUTPUT: + +2<br> +4<br> +6<br> +8<br> + + + + 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 contents. 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 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) + + +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:password@ftp.domain.com/path/to/currentheadlines.txt"} + +{* assign the fetched contents to a template variable *} +{fetch file="http://www.myweather.com/68502/" assign="weather"} +{if $weather ne ""} + <b>{$weather}</b> +{/if} + + + + html_options + + + + + + + + + + Attribute Name + Type + Required + Default + Description + + + + + values + array + Yes, unless using options attribute + n/a + an array of values for dropdown + + + output + array + Yes, unless using options attribute + n/a + an array of output for dropdown + + + selected + string + No + empty + the selected array element + + + options + associative array + Yes, unless using values and output + n/a + an associative array of values and output + + + + + + html_options is a custom function that creates html option + lists with provided data. It takes care of which item is + selected by default as well. Required attributes are values + and output, unless you use options instead. + + + NOTE: As of Smarty 1.4.5, html_options now outputs xhtml compatible + code. + + +html_options + +{* assume that $cust_ids, and $cust_names are arrays of values, + and $customer_id may or may not be set to a value *} + +<select name=customer_id> + {html_options values=$cust_ids selected=$customer_id output=$cust_names} +</select> + + +{* an alternative method is to pass the values & output as an associative array into + options. $customer_options is an associative array in this example. This + functionality was added to Smarty 1.3.0 *} + +<select name=customer_id> + {html_options options=$customer_options selected=$customer_id} +</select> + + +OUTPUT: + +<select name=customer_id> + <option value="1000">Joe Schmoe<option> + <option value="1001" selected>Jack Smith<option> + <option value="1002">Jane Johnson<option> + <option value="1003">Charlie Brown<option> +</select> + + + + html_select_date + + + + + + + + + + Attribute Name + Type + Required + Default + Description + + + + + prefix + string + No + Date_ + what to prefix the var name with + + + time + timestamp + No + current time + what date/time to use + + + start_year + string + No + current year + the first year in the dropdown + + + end_year + string + No + same as start_year + the last year in the dropdown + + + display_days + boolean + No + true + whether to display days or not + + + display_months + boolean + No + true + whether to display months or not + + + display_years + boolean + No + true + whether to display years or not + + + month_format + string + No + %B + what format the month should be in (strftime) + + + day_format + string + No + %02d + what format the day should be in (sprintf) + + + year_as_text + boolean + No + false + whether or not to display the year as text + + + reverse_years + boolean + No + false + display years in reverse order + + + field_array + string + No + null + + if a name is given, the select boxes will be drawn + such that the results will be returned to PHP in the + form of name[Day], name[Year], name[Month]. + + + + day_size + string + No + null + adds size attribute to select tag if given + + + month_size + string + No + null + adds size attribute to select tag if given + + + year_size + string + No + null + adds size attribute to select tag if given + + + all_extra + string + No + null + adds extra attributes to all select/input tags if + given + + + day_extra + string + No + null + adds extra attributes to select/input tags if + given + + + month_extra + string + No + null + adds extra attributes to select/input tags if + given + + + year_extra + string + No + null + adds extra attributes to select/input tags if + given + + + field_order + string + No + MDY + the order in which to display the fields + + + field_separator + string + No + \n + string printed between different fields + + + + + + html_select_date is a custom function that creates date dropdowns + for you. It can display any or all of year, month, and day. + + + NOTE: reverse_years, field_array, day_size, month_size, year_size, + all_extra, day_extra, month_extra, year_extra, field_order, + field_separator added in Smarty 1.4.5. + + +html_select_date + +{html_select_date} + + +OUTPUT: + +<select name="Date_Month"> +<option value="1">January</option> +<option value="2">February</option> +<option value="3">March</option> +<option value="4">April</option> +<option value="5">May</option> +<option value="6">June</option> +<option value="7">July</option> +<option value="8">August</option> +<option value="9">September</option> +<option value="10">October</option> +<option value="11">November</option> +<option value="12" selected>December</option> +</select> +<select name="Date_Day"> +<option value="1">01</option> +<option value="2">02</option> +<option value="3">03</option> +<option value="4">04</option> +<option value="5">05</option> +<option value="6">06</option> +<option value="7">07</option> +<option value="8">08</option> +<option value="9">09</option> +<option value="10">10</option> +<option value="11">11</option> +<option value="12">12</option> +<option value="13" selected>13</option> +<option value="14">14</option> +<option value="15">15</option> +<option value="16">16</option> +<option value="17">17</option> +<option value="18">18</option> +<option value="19">19</option> +<option value="20">20</option> +<option value="21">21</option> +<option value="22">22</option> +<option value="23">23</option> +<option value="24">24</option> +<option value="25">25</option> +<option value="26">26</option> +<option value="27">27</option> +<option value="28">28</option> +<option value="29">29</option> +<option value="30">30</option> +<option value="31">31</option> +</select> +<select name="Date_Year"> +<option value="2001" selected>2001</option> +</select> + + + + +html_select_date + + +{html_select_date prefix="StartDate" time=$time start_year=1995 end_year=2001 display_days=false} + +OUTPUT: + +<select name="StartDateMonth"> +<option value="1">January</option> +<option value="2">February</option> +<option value="3">March</option> +<option value="4">April</option> +<option value="5">May</option> +<option value="6">June</option> +<option value="7">July</option> +<option value="8">August</option> +<option value="9">September</option> +<option value="10">October</option> +<option value="11">November</option> +<option value="12" selected>December</option> +</select> +<select name="StartDateYear"> +<option value="1999">1995</option> +<option value="1999">1996</option> +<option value="1999">1997</option> +<option value="1999">1998</option> +<option value="1999">1999</option> +<option value="2000" selected>2000</option> +<option value="2001">2001</option> +</select> + + + + html_select_time + + + + + + + + + + Attribute Name + Type + Required + Default + Description + + + + + prefix + string + No + Time_ + what to prefix the var name with + + + time + timestamp + No + current time + what date/time to use + + + display_hours + boolean + No + true + whether or not to display hours + + + display_minutes + boolean + No + true + whether or not to display minutes + + + display_seconds + boolean + No + true + whether or not to display seconds + + + display_meridian + boolean + No + true + whether or not to display meridian (am/pm) + + + use_24_hours + boolean + No + true + whether or not to use 24 hour clock + + + minute_interval + integer + No + 1 + number interval in minute dropdown + + + second_interval + integer + No + 1 + number interval in second dropdown + + + field_array + string + No + n/a + outputs values to array of this name + + + + + + html_select_time is a custom function that creates time dropdowns + for you. It can display any or all of hour, minute, second and + meridian. + + +html_select_time + +{html_select_time use_24_hours=true} + + +OUTPUT: + +<select name="Time_Hour"> +<option value="00">00</option> +<option value="01">01</option> +<option value="02">02</option> +<option value="03">03</option> +<option value="04">04</option> +<option value="05">05</option> +<option value="06">06</option> +<option value="07">07</option> +<option value="08">08</option> +<option value="09" selected>09</option> +<option value="10">10</option> +<option value="11">11</option> +<option value="12">12</option> +<option value="13">13</option> +<option value="14">14</option> +<option value="15">15</option> +<option value="16">16</option> +<option value="17">17</option> +<option value="18">18</option> +<option value="19">19</option> +<option value="20">20</option> +<option value="21">21</option> +<option value="22">22</option> +<option value="23">23</option> +</select> +<select name="Time_Minute"> +<option value="00">00</option> +<option value="01">01</option> +<option value="02">02</option> +<option value="03">03</option> +<option value="04">04</option> +<option value="05">05</option> +<option value="06">06</option> +<option value="07">07</option> +<option value="08">08</option> +<option value="09">09</option> +<option value="10">10</option> +<option value="11">11</option> +<option value="12">12</option> +<option value="13">13</option> +<option value="14">14</option> +<option value="15">15</option> +<option value="16">16</option> +<option value="17">17</option> +<option value="18">18</option> +<option value="19">19</option> +<option value="20" selected>20</option> +<option value="21">21</option> +<option value="22">22</option> +<option value="23">23</option> +<option value="24">24</option> +<option value="25">25</option> +<option value="26">26</option> +<option value="27">27</option> +<option value="28">28</option> +<option value="29">29</option> +<option value="30">30</option> +<option value="31">31</option> +<option value="32">32</option> +<option value="33">33</option> +<option value="34">34</option> +<option value="35">35</option> +<option value="36">36</option> +<option value="37">37</option> +<option value="38">38</option> +<option value="39">39</option> +<option value="40">40</option> +<option value="41">41</option> +<option value="42">42</option> +<option value="43">43</option> +<option value="44">44</option> +<option value="45">45</option> +<option value="46">46</option> +<option value="47">47</option> +<option value="48">48</option> +<option value="49">49</option> +<option value="50">50</option> +<option value="51">51</option> +<option value="52">52</option> +<option value="53">53</option> +<option value="54">54</option> +<option value="55">55</option> +<option value="56">56</option> +<option value="57">57</option> +<option value="58">58</option> +<option value="59">59</option> +</select> +<select name="Time_Second"> +<option value="00">00</option> +<option value="01">01</option> +<option value="02">02</option> +<option value="03">03</option> +<option value="04">04</option> +<option value="05">05</option> +<option value="06">06</option> +<option value="07">07</option> +<option value="08">08</option> +<option value="09">09</option> +<option value="10">10</option> +<option value="11">11</option> +<option value="12">12</option> +<option value="13">13</option> +<option value="14">14</option> +<option value="15">15</option> +<option value="16">16</option> +<option value="17">17</option> +<option value="18">18</option> +<option value="19">19</option> +<option value="20">20</option> +<option value="21">21</option> +<option value="22">22</option> +<option value="23" selected>23</option> +<option value="24">24</option> +<option value="25">25</option> +<option value="26">26</option> +<option value="27">27</option> +<option value="28">28</option> +<option value="29">29</option> +<option value="30">30</option> +<option value="31">31</option> +<option value="32">32</option> +<option value="33">33</option> +<option value="34">34</option> +<option value="35">35</option> +<option value="36">36</option> +<option value="37">37</option> +<option value="38">38</option> +<option value="39">39</option> +<option value="40">40</option> +<option value="41">41</option> +<option value="42">42</option> +<option value="43">43</option> +<option value="44">44</option> +<option value="45">45</option> +<option value="46">46</option> +<option value="47">47</option> +<option value="48">48</option> +<option value="49">49</option> +<option value="50">50</option> +<option value="51">51</option> +<option value="52">52</option> +<option value="53">53</option> +<option value="54">54</option> +<option value="55">55</option> +<option value="56">56</option> +<option value="57">57</option> +<option value="58">58</option> +<option value="59">59</option> +</select> +<select name="Time_Meridian"> +<option value="am" selected>AM</option> +<option value="pm">PM</option> +</select> + + + + math + + + + + + + + + + Attribute Name + Type + Required + Default + Description + + + + + equation + string + Yes + n/a + the equation to execute + + + format + string + No + n/a + the format of the result (sprintf) + + + var + numeric + Yes + n/a + equation variable value + + + assign + string + No + n/a + template variable the output will be assigned to + + + [var ...] + numeric + Yes + n/a + equation variable value + + + + + + math allows the template designer to do math equations in the + template. Any numeric template variables may be used in the + equations, and the result is printed in place of the tag. The + variables used in the equation are passed as parameters, which can + be template variables or static values. +, -, /, *, abs, ceil, cos, + exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, + srans and tan are all valid operators. Check the PHP documenation + for further information on these math functions. + + + If you supply the special "assign" attribute, the output of the + math function will be assigned to this template variable instead of + being output to the template. + + +math + +{* $height=4, $width=5 *} + +{math equation="x + y" x=$height y=$width} + +OUTPUT: + +9 + + +{* $row_height = 10, $row_width = 20, #col_div# = 2, assigned in template *} + +{math equation="height * width / division" + height=$row_height + width=$row_width + division=#col_div#} + +OUTPUT: + +100 + + +{* you can use parenthesis *} + +{math equation="(( x + y ) / z )" x=2 y=10 z=2} + +OUTPUT: + +6 + + +{* you can supply a format parameter in sprintf format *} + +{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"} + +OUTPUT: + +9.44 + + + + popup_init + + popup is an integration of overLib, a library used for popup + windows. These are used for context sensitive information, such as + help windows or tooltips. popup_init must be called once at the + top of any page you plan on using the popup function. overLib + was written by Erik Bosrup, and the homepage is located at + http://www.bosrup.com/web/overlib/. + + + This was added to Smarty 1.4.4. + + + + popup + + + + + + + + + + Attribute Name + Type + Required + Default + Description + + + + + text + string + Yes + n/a + the text/html to display in the popup window + + + trigger + string + No + onMouseOver + What is used to trigger the popup window. Can be + one of onMouseOver or onClick + + + sticky + boolean + No + false + Makes the popup stick around until closed + + + caption + string + No + n/a + sets the caption to title + + + fgcolor + string + No + n/a + color of the inside of the popup box + + + bgcolor + string + No + n/a + color of the border of the popup box + + + textcolor + string + No + n/a + sets the color of the text inside the box + + + capcolor + string + No + n/a + sets color of the box's caption + + + closecolor + string + No + n/a + sets the color of the close text + + + textfont + string + No + n/a + sets the font to be used by the main text + + + captionfont + string + No + n/a + sets the font of the caption + + + closefont + string + No + n/a + sets the font for the "Close" text + + + textsize + string + No + n/a + sets the size of the main text's font + + + captionsize + string + No + n/a + sets the size of the caption's font + + + closesize + string + No + n/a + sets the size of the "Close" text's font + + + width + integer + No + n/a + sets the width of the box + + + height + integer + No + n/a + sets the height of the box + + + left + boolean + No + false + makes the popups go to the left of the mouse + + + right + boolean + No + false + makes the popups go to the right of the mouse + + + center + boolean + No + false + makes the popups go to the center of the mouse + + + above + boolean + No + false + makes the popups go above the mouse. NOTE: only + possible when height has been set + + + below + boolean + No + false + makes the popups go below the mouse + + + border + integer + No + n/a + makes the border of the popups thicker or thinner + + + offsetx + integer + No + n/a + how far away from the pointer the popup will show + up, horizontally + + + offsety + integer + No + n/a + how far away from the pointer the popup will show + up, vertically + + + fgbackground + url to image + No + n/a + defines a picture to use instead of color for the + inside of the popup. + + + bgbackground + url to image + No + n/a + defines a picture to use instead of color for the + border of the popup. NOTE: You will want to set bgcolor + to "" or the color will show as well. NOTE: When having + a Close link, Netscape will re-render the table cells, + making things look incorrect + + + closetext + string + No + n/a + sets the "Close" text to something else + + + noclose + boolean + No + n/a + does not display the "Close" text on stickies + with a caption + + + status + string + No + n/a + sets the text in the browsers status bar + + + autostatus + boolean + No + n/a + sets the status bar's text to the popup's text. + NOTE: overrides status setting + + + autostatuscap + string + No + n/a + sets the status bar's text to the caption's text. + NOTE: overrides status and autostatus settings + + + inarray + integer + No + n/a + tells overLib to read text from this index in + the ol_text array, located in overlib.js. This + parameter can be used instead of text + + + caparray + integer + No + n/a + tells overLib to read the caption from this index + in the ol_caps array + + + capicon + url + No + n/a + displays the image given before the popup caption + + + snapx + integer + No + n/a + snaps the popup to an even position in a + horizontal grid + + + snapy + integer + No + n/a + snaps the popup to an even position in a + vertical grid + + + fixx + integer + No + n/a + locks the popups horizontal position Note: + overrides all other horizontal placement + + + fixy + integer + No + n/a + locks the popups vertical position Note: + overrides all other vertical placement + + + background + url + No + n/a + sets image to be used instead of table box + background + + + padx + integer,integer + No + n/a + pads the background image with horizontal + whitespace for text placement. Note: this is a two + parameter command + + + pady + integer,integer + No + n/a + pads the background image with vertical + whitespace for text placement. Note: this is a two + parameter command + + + fullhtml + boolean + No + n/a + allows you to control the html over a background + picture completely. The html code is expected in the "text" + attribute + + + frame + string + No + n/a + controls popups in a different frame. See the + overlib page for more info on this function + + + timeout + string + No + n/a + calls the specified javascript function and takes + the return value as the text that should be displayed in + the popup window + + + delay + integer + No + n/a + makes that popup behave like a tooltip. It will + popup only after this delay in milliseconds + + + hauto + boolean + No + n/a + automatically determine if the popup should be to + the left or right of the mouse. + + + vauto + boolean + No + n/a + automatically determine if the popup should be + above or below the mouse. + + + + + + popup is used to create javascript popup windows. + + +popup + +{* popup_init must be called once at the top of the page *} +{popup_init} + +{* create a link with a popup window when you move your mouse over *} +<A href="mypage.html" {popup text="This link takes you to my page!"}>mypage</A> + +{* you can use html, links, etc in your popup text *} +<A href="mypage.html" {popup sticky=true caption="mypage contents" +text="<UL><LI>links<LI>pages<LI>images</UL>" snapx=10 snapy=10}>mypage</A> + +OUTPUT: + +(See the Smarty official web site for working examples.) + + + + + + + + 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 + +# global variables +pageTitle = "Main Menu" +bodyBgColor = #000000 +tableBgColor = #000000 +rowBgColor = #00ff00 + +[Customer] +pageTitle = "Customer Info" + +[Login] +pageTitle = "Login" +focus = "username" +Intro = """This is a value that spans more + than one line. you must enclose + it in triple quotes.""" + +# hidden section +[.Database] +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. + + + + + + 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. + + + 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. + + + + diff --git a/docs/getting-started.sgml b/docs/getting-started.sgml new file mode 100644 index 00000000..563d41cf --- /dev/null +++ b/docs/getting-started.sgml @@ -0,0 +1,198 @@ + + Getting Started + + Overview + + What is Smarty? + + Smarty is a template engine for PHP. One of the unique aspects about + Smarty is that it compiles the template files into native PHP scripts + upon the first invocation. After that, it just executes the compiled + PHP scripts. 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 Cache (http://www.zend.com) or APC + (http://apc.communityconnect.com). + + + 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 ...} expression 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 (new in 1.3.0) + Arbitrary template sources (new in 1.4.0) + Custom cache handling functions (new in 1.4.7) + + + + + How Smarty works + + Compiling + + Smarty compiles the templates into native PHP code on-the-fly. The actual + PHP scripts that are generated are created implicitly, so theoretically you + should never have to worry about touching these files, or even know of their + existence. The exception to this is debugging Smarty template syntax errors, + discussed later in this document. + + + + + Caching + + Smarty can cache the output of your generated templates. By default + this is disabled. If you enable + caching, Smarty will store a copy of the generated template + output, and use this until the copy expires, regenerating a new + one. The default cache expire time can be configured from the + class. The exception to the rule is the insert tag. Anything + generated by the insert tag is not cached, but run dynamically on + every invocation, even within cached content. + + + TECHNICAL NOTE: Any time you change a template, change values in + config files or change the content that gets displayed in a + template, you can turn on compile_check to regenerate the caches + that are affected, or wait for the cache to expire to see the + results of the changes. You clear caches manually by deleting files + from the cache directory, programatically with clear_cache or clear_all_cache, or turn on + $compile_check (or $force_compile). + + + TECHNICAL NOTE: As of Smarty 1.4.6, if you have caching enabled AND + you have compile_check enabled, the cached file will regenerate if + an involved template or config file has been modified, regardless + of the cache expire time. This results in a slight performance hit + since it has to check the templates and config files for + modification times. Therefore if you are not actively changing + templates or config files, it is advisable to leave compile_check + off. As of Smarty 1.4.7, enabling $force_compile will cause cache + files to always be regenerated. + + + + + + + Installation + + + Requirements + + Smarty requires PHP 4.0.4pl1 or later. See the + BUGS section for caveats. + + + + + Installing Smarty + + Installing Smarty is fairly straightforward, there are a few things to + be aware of. Smarty creates PHP scripts from the templates. This + usually means allowing user "nobody" (or whomever the web server runs + as) to have permission to write the files. Each installation of a + Smarty application minimally needs a templates directory and a compiled + templates directory. If you use configuration files you will also need + a directory for those. By default these are named "templates", + "templates_c" and "configs" respectively. If you plan on using caching, + you will need to create a "cache" directory, also with permission to + write files. + + + TECHNICAL NOTE: You can get around the need to allow the web server + user write access to compile templates. Smarty needs to compile the + templates only once. This can be done from the command line, using the + CGI version of PHP. example: "php -q index.php". Once the templates are + compiled, they should run fine from the web environment. If you change + a template, you must recompile from the command line again. If you do + not have the CGI version of PHP available and you are concerned about + world-writable directory access, you can chmod 777 the compile_dir, let + the templates compile once as the web server user, then change the + directory mode to 755. If you are using the caching feature of Smarty, + the cache directory must always have write access for the web server + user. + + + TECHNICAL NOTE: If you do not have access to the php.ini file, you can + change non-server settings (such as your include_path) with the + ini_set() command (available in PHP 4.0.4 or later.) example: + ini_set("include_path",".:/usr/local/lib/php"); + + + Copy the Smarty.class.php, Smarty.addons.php and Config_File.class.php + scripts to a directory that is in your PHP include_path. NOTE: PHP will + try to create a directory alongside the executing script called + "templates_c". Be sure that directory permissions allow this to happen. + You will see PHP error messages if this fails. You can also create the + directory yourself before hand, and change the file ownership + accordingly. See below. + + + TECHNICAL NOTE: If you don't want to use include_path to find the + Smarty files, you can set the SMARTY_DIR constant to the full path to + your Smarty library files. Be sure the path ends with a slash! + + + Example of installing Smarty + +# be sure you are in the web server document tree +# this assumes your web server runs as user "nobody" +# and you are in a un*x environment +gtar -zxvf Smarty-[version].tar.gz +mkdir templates_c +chown nobody:nobody templates_c +chmod 700 templates_c +# if you are using caching, do the following +mkdir cache +chown nobody:nobody cache +chmod 700 cache + + + Next, try running the index.php script from your web browser. + + + + Constants + + + + SMARTY_DIR + + This should be the full system path to the location of the Smarty + class files. If this is not defined, then Smarty will attempt to + determine the appropriate value automatically. If defined, the path + must end with a slash. + + + SMARTY_DIR + +// set path to Smarty directory +define("SMARTY_DIR","/usr/local/lib/php/Smarty/"); + +require_once(SMARTY_DIR."Smarty.class.php"); + + + + + diff --git a/docs/html-common.dsl b/docs/html-common.dsl new file mode 100644 index 00000000..29a99f06 --- /dev/null +++ b/docs/html-common.dsl @@ -0,0 +1,336 @@ +;; -*- Scheme -*- +;; +;; $Id$ +;; + +;; Returns the depth of the auto-generated TOC (table of contents) that +;; should be made at the nd-level +(define (toc-depth nd) + (if (string=? (gi nd) (normalize "book")) + 3 ; the depth of the top-level TOC + 1 ; the depth of all other TOCs + )) + + + + + + +(element (funcdef function) + ($bold-seq$ + (make sequence + (process-children) + ) + ) + ) + + +(define (is-true-optional nl) + (and (equal? (gi (parent nl)) (normalize "parameter")) + (equal? 0 (string-length (strip (data (preced nl))))) + (equal? 0 (string-length (strip (data (follow nl))))) + ) + ) + + +(define (has-true-optional nl) + (is-true-optional + (node-list-first-element + (select-elements + (descendants nl) + (normalize "optional")) + ) + ) + ) + + +(define (count-true-optionals nl) + (let loop + ((result 0) + (nl (select-elements (descendants nl) (normalize "optional"))) + ) + (if(node-list-empty? nl) + result + (if(is-true-optional(node-list-first nl)) + (loop (+ result 1) (node-list-rest nl)) + (loop result (node-list-rest nl)) + ) + ) + ) + ) + + +;; there are two different kinds of optionals +;; optional parameters and optional parameter parts +;; an optional parameter is identified by an optional tag +;; with a parameter tag as its parent +;; and only whitespace between them +(element optional + ;;check for true optional parameter + (if (is-true-optional (current-node)) + ;; yes - handle '[...]' in paramdef + (process-children-trim) + ;; no - do '[...]' output + (make sequence + (literal %arg-choice-opt-open-str%) + (process-children-trim) + (literal %arg-choice-opt-close-str%) + ) + ) + ) + +;; now this is going to be tricky +(element paramdef + (make sequence + ;; special treatment for first parameter in funcsynopsis + (if (equal? (child-number (current-node)) 1) + ;; is first ? + (make sequence + ;; start parameter list + (literal "(") + ;; is optional ? + ( if (has-true-optional (current-node)) + (literal %arg-choice-opt-open-str%) + (empty-sosofo) + ) + ) + ;; not first + (empty-sosofo) + ) + + ;; + (process-children-trim) + + ;; special treatment for last parameter + (if (equal? (gi (ifollow (current-node))) (normalize "paramdef")) + ;; more parameters will follow + (make sequence + ;; next is optional ? + ( if (has-true-optional (ifollow (current-node))) + ;; optional + (make sequence + (literal " ") + (literal %arg-choice-opt-open-str%) + ) + ;; not optional + (empty-sosofo) + ) + (literal ", " ) + ) + ;; last parameter + (make sequence + (literal + (let loop ((result "")(count (count-true-optionals (parent (current-node))))) + (if (<= count 0) + result + (loop (string-append result %arg-choice-opt-close-str%)(- count 1)) + ) + ) + ) + ( literal ")" ) + ) + ) + ) + ) + + +(element function + (let* ((function-name (data (current-node))) + (linkend + (string-append + "function." + (string-replace + (string-replace function-name "_" "-") + "::" "."))) + (target (element-with-id linkend)) + (parent-gi (gi (parent)))) + (cond + ;; function names should be plain in FUNCDEF + ((equal? parent-gi "funcdef") + (process-children)) + + ;; if a valid ID for the target function is not found, or if the + ;; FUNCTION tag is within the definition of the same function, + ;; make it bold, add (), but don't make a link + ((or (node-list-empty? target) + (equal? (case-fold-down + (data (node-list-first + (select-elements + (node-list-first + (children + (select-elements + (children + (ancestor-member (parent) (list "refentry"))) + "refnamediv"))) + "refname")))) + function-name)) + ($bold-seq$ + (make sequence + (process-children) + (literal "()")))) + + ;; else make a link to the function and add () + (else + (make element gi: "A" + attributes: (list + (list "HREF" (href-to target))) + ($bold-seq$ + (make sequence + (process-children) + (literal + ) + (literal "()")))))))) + + +(element classname + (let* ((class-name (data (current-node))) + (linkend + (string-append + "class." + (string-replace + (case-fold-down class-name) "_" "-"))) + (target (element-with-id linkend)) + (parent-gi (gi (parent)))) + (cond + ;; function names should be plain in SYNOPSIS + ((equal? parent-gi "synopsis") + (process-children)) + + ;; if a valid ID for the target class is not found, or if the + ;; CLASSNAME tag is within the definition of the same class, + ;; make it bold, but don't make a link + ((or (node-list-empty? target) + (equal? (case-fold-down + (data (node-list-first + (select-elements + (node-list-first + (children + (select-elements + (children + (ancestor-member (parent) (list "refentry"))) + "refnamediv"))) + "refname")))) + class-name)) + ($bold-seq$ + (process-children))) + + ;; else make a link to the function and add () + (else + (make element gi: "A" + attributes: (list + (list "HREF" (href-to target))) + ($bold-seq$ + (process-children))))))) + + +(element constant + (let* ((constant-name (data (current-node))) + (linkend + (string-append "constant." + (case-fold-down + (string-replace constant-name "_" "-")))) + (target (element-with-id linkend)) + (parent-gi (gi (parent)))) + (cond +; ;; constant names should be plain in FUNCDEF +; ((equal? parent-gi "funcdef") +; (process-children)) + + ;; if a valid ID for the target constant is not found, or if the + ;; CONSTANT tag is within the definition of the same constant, + ;; make it bold, add (), but don't make a link + ((or (node-list-empty? target) + (equal? (case-fold-down + (data (node-list-first + (select-elements + (node-list-first + (children + (select-elements + (children + (ancestor-member (parent) (list "refentry"))) + "refnamediv"))) + "refname")))) + constant-name)) + ($bold-mono-seq$ + (process-children))) + + ;; else make a link to the function and add () + (else + (make element gi: "A" + attributes: (list + (list "HREF" (href-to target))) + ($bold-mono-seq$ + (process-children))))))) + + +(element example + (make sequence + (make element gi: "TABLE" + attributes: (list + (list "WIDTH" "100%") + (list "BORDER" "0") + (list "CELLPADDING" "0") + (list "CELLSPACING" "0") + (list "CLASS" "EXAMPLE")) + (make element gi: "TR" + (make element gi: "TD" + ($formal-object$)))))) + + +(element (paramdef parameter) + (make sequence + font-posture: 'italic + (process-children-trim) + ) + ) + +(mode book-titlepage-recto-mode + (element authorgroup + (process-children)) + + (element author + (let ((author-name (author-string)) + (author-affil (select-elements (children (current-node)) + (normalize "affiliation")))) + (make sequence + (make element gi: "DIV" + attributes: (list (list "CLASS" (gi))) + (literal author-name)) + (process-node-list author-affil)))) + ) + +(define (chunk-element-list) + (list (normalize "preface") + (normalize "chapter") + (normalize "appendix") + (normalize "article") + (normalize "glossary") + (normalize "bibliography") + (normalize "index") + (normalize "colophon") + (normalize "setindex") + (normalize "reference") + (normalize "refentry") + (normalize "part") + (normalize "sect1") + (normalize "sect2") + (normalize "section") + (normalize "book") ;; just in case nothing else matches... + (normalize "set") ;; sets are definitely chunks... + )) + +(define ($section-body$) + (make element gi: "DIV" + attributes: (list (list "CLASS" (gi))) + ($section-separator$) + ($section-title$) + + (if (or (not (node-list-empty? (select-elements (children (current-node)) + (normalize "sect2")))) + (not (node-list-empty? (select-elements (children (current-node)) + (normalize "sect3"))))) + (build-toc (current-node) 1) + (empty-sosofo)) + + (process-children))) + diff --git a/docs/html.dsl b/docs/html.dsl new file mode 100644 index 00000000..e312da30 --- /dev/null +++ b/docs/html.dsl @@ -0,0 +1,21 @@ + + + +]> + + + + + +(define %html-ext% ".html") + +&html-common.dsl; +&common.dsl; + + + + + + + diff --git a/docs/manual.sgml b/docs/manual.sgml new file mode 100644 index 00000000..62ae6d1c --- /dev/null +++ b/docs/manual.sgml @@ -0,0 +1,34 @@ + + + + + +]> + + + + Smarty - the compiling PHP template engine + + + MonteOhrt <monte@ispi.net> + + + AndreiZmievski <andrei@php.net> + + + Version 2.0 + + 2001 + 2002 + ispi of Lincoln, Inc. + + + + &preface; + &getting.started; + &smarty.for.designers; + &smarty.for.programmers; + &appendixes; + + diff --git a/docs/preface.sgml b/docs/preface.sgml new file mode 100644 index 00000000..188cc51d --- /dev/null +++ b/docs/preface.sgml @@ -0,0 +1,69 @@ + + Preface + + 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 programming/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 dynamic 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 finishing 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 complicated 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 existence (note: this + class was never submitted to the public). It was a class that did + almost 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 parsing 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... + + diff --git a/docs/programmers.sgml b/docs/programmers.sgml new file mode 100644 index 00000000..445c38f8 --- /dev/null +++ b/docs/programmers.sgml @@ -0,0 +1,2030 @@ + + Smarty For Programmers + + Smarty API + + + Variables + + + $template_dir + + This is the name of the default template directory. If you do + not supply a resource type when including files, they will be + found here. By default this is "./templates", meaning that it + will look for the templates directory in the same directory as + the executing php script. + + + TECHNICAL NOTE: It is not mandatory to put this directory under + the web server document root. + + + + $compile_dir + + This is the name of the directory where compiled templates are + located. By default this is "./templates_c", meaning that it + will look for the compile directory in the same directory as + the executing php script. This was added to Smarty version + 1.2.1. + + + TECHNICAL NOTE: This setting must be either a relative or + absolute path. include_path is not used for writing files. + + + TECHNICAL NOTE: It is not mandatory to put this directory under + the web server document root. + + + + $config_dir + + This is the directory used to store config files used in the + templates. Default is "./configs", meaning that it will look + for the configs directory in the same directory as the + executing php script. + + + TECHNICAL NOTE: It is not mandatory to put this directory under + the web server document root. + + + + $plugins_dir + + This is the directory where Smarty will look for the plugins that + it needs. The directory must be relative to the directory where + Smarty itself is installed. Default is "plugins". There can be + only one plugins directory. + + + + $debugging + + This enables the debugging console. + The console is a javascript window that informs you of the + included templates and assigned variables for the current + template page. + + + NOTE: This was added to Smarty 1.4.3. + + + + $debug_tpl + + This is the name of the template file used for the debugging + console. + + + NOTE: This was added to Smarty 1.4.3. + + + + $debugging_ctrl + + This allows alternate ways to enable debugging. NONE means no + alternate methods are allowed. URL means when the keyword + SMARTY_DEBUG is found in the QUERY_STRING, debugging is enabled + for that invocation of the script. If $debugging is true, this + value is ignored. + + + NOTE: This was added to Smarty 1.4.4. + + + + $global_assign + + This is a list of variables that are always implicitly assigned + to the template engine. This is handy for making global + variables or server variables available to all templates + without having to manually assign them. Each element in the + $global_assign should be either a name of the global variable, + or a key/value pair, where the key is the name of the global + array and the value is the array of variables to be assigned + from that global array. $SCRIPT_NAME is globally assigned by + default from $HTTP_SERVER_VARS. + + + TECHNICAL NOTE: Server variables can be accessed through the + $smarty variable, such as {$smarty.server.SCRIPT_NAME}. See the + section on the + $smarty variable. + + + + $undefined + + This sets the value of $undefined for Smarty, default is null. + Currently this is only used to set undefined variables in + $global_assign to a default value. + + + + $compile_check + + Upon each invocation of the PHP application, Smarty tests to + see if the current template has changed (later time stamp) + since the last time it was compiled. If it has changed, it + recompiles that template. As of 1.4.0, if the template has not + been compiled, it will compile regardless of this setting. By + default this variable is set to true. Once an application is + put into production (templates won't be changing), the + compile_check step is no longer needed. Be sure to set + $compile_check to "false" to improve performance! Note that if + you change this to "false" and a template file is changed, you + will *not* see the change since the template will not get + recompiled. If caching is enabled and compile_check is enabled, + then the cache files will get regenerated if an involved + template file was updated. See $force_compile or clear_compiled_tpl. + + + + $force_compile + + This forces Smarty to (re)compile templates on every + invocation. This setting overrides $compile_check. By default + this is disabled. This is handy for development and debugging. + It should never be used in a production environment. If caching + is enabled, the cache file(s) will be regenerated every time. + + + + $caching + + This tells Smarty whether or not to cache the output of the + templates. By default this is set to false. If your templates + generate redundant redundant content over and over again and + again repeatedly, it is advisable to turn on caching. This will + result in significant performance gains. You can also have + multiple caches for the same template. See is_cached for details. This was + added to Smarty 1.3.0. + + + If $compile_check is enabled, the cached content will be + regenerated if any of the involved templates are changed. (new + to 1.4.6). If $force_compile is enabled, the cached content + will always be regenerated. (added to Smarty 1.4.7) + + + + $cache_dir + + This is the name of the directory where template caches are + stored. By default this is "./cache", meaning that it will look + for the cache directory in the same directory as the executing + php script. You can also use your own custom cache handler + function to control cache files, which will ignore this + setting. (added to Smarty 1.3.0) + + + TECHNICAL NOTE: This setting must be either a relative or + absolute path. include_path is not used for writing files. + + + TECHNICAL NOTE: It is not mandatory to put this directory under + the web server document root. + + + + $cache_lifetime + + This is the length of time in seconds that a template cache is + valid. Once this time has expired, the cache will be + regenerated. $caching must be set to "true" for this setting to + work. You can also force the cache to expire with clear_all_cache. (added to + Smarty 1.3.0) + + + + $cache_handler_func + + You can supply a custom function to handle cache files instead + of using the built-in method using the $cache_dir. See the + custom cache handler function section for details. + + + + $cache_modified_check + + If set to true, Smarty will respect the If-Modified-Since + header sent from the client. If the cached file timestamp has + not changed since the last visit, then a "304 Not Modified" + header will be sent instead of the content. This works only on + cached content without {insert} tags. + + + + $default_template_handler_func + + This function is called when a template cannot be obtained from + its resource. (added to Smarty 1.5.2) + + + + $php_handling + + This tells Smarty how to handle PHP code embedded in the + tempalates. There are four possible settings, default being + SMARTY_PHP_PASSTHRU. Note that this does NOT affect php code + within {php}{/php} + tags in the template. + + + SMARTY_PHP_PASSTHRU - Smarty echos tags as-is. + SMARTY_PHP_QUOTE - Smarty quotes the tags as + html entities. + SMARTY_PHP_REMOVE - Smarty removes the tags from + the templates. + SMARTY_PHP_ALLOW - Smarty will execute the tags + as PHP code. + + + NOTE: Embedding PHP code into templates is highly discouraged. + Use custom functions or + modifiers instead. + + + + $security + + $security true/false, default is false. Security is good for + situations when you have untrusted parties editing the templates + (via ftp for example) and you want to reduce the risk of system + security compromises through the template language. Turning on + security enforces the following rules to the template language, + unless specifially overridden with $security_settings: + + + If $php_handling is set to SMARTY_PHP_ALLOW, this is + implicitly changed to SMARTY_PHP_PASSTHRU + PHP functions are not allowed in IF statements, + except those specified in the $security_settings + templates can only be included from directories + listed in the $secure_dir array + local files can only be fetched from directories + listed in the $secure_dir array using {fetch} + {php}{/php} tags are not allowed + PHP functions are not allowed as modifiers, except + those specified in the $security_settings + + + NOTE: Security features were added to Smarty 1.4.3. + + + + $secure_dir + + This is an array of all local directories that are considered + secure. {include} and {fetch} use this when security is enabled. + + + + $security_settings + + These are used to override or specify the security settings when + security is enabled. These are the possible settings: + + + PHP_HANDLING - true/false. If set to true, the + $php_handling setting is not checked for security. + IF_FUNCS - This is an array of the names of permitted + PHP functions in IF statements. + INCLUDE_ANY - true/false. If set to true, any + template can be included from the file system, regardless of the + $secure_dir list. + PHP_TAGS - true/false. If set to true, {php}{/php} + tags are permitted in the templates. + MODIFIER_FUNCS - This is an array of the names of permitted + PHP functions used as variable modifiers. + + + + $trusted_dir + + $trusted_dir is only for use when $security is enabled. This is an array + of all directories that are considered trusted. Trusted directories are + where you keep php scripts that are executed directly from the templates + with {include_php}. + + + + $left_delimiter + + This is the left delimiter used by the template language. + Default is "{". + + + + $right_delimiter + + This is the right delimiter used by the template language. + Default is "}". + + + + $show_info_header + + Shows an HTML comment at the beginning of the templates output, + displaying smarty version and date generated. Default is false. + + + + $show_info_include + + Shows an HTML comment before and after each included template. + Default is false. + + + + $compiler_class + + Specifies the name of the compiler class that Smarty will use + to compile the templates. The default is 'Smarty_Compiler'. For + advanced users only. + + + + $request_vars_order + + The order in which request variables are registered, similar to + variables_order in php.ini + + + + $compile_id + + Persistant compile identifier. As an alternative to passing the + same compile_id to each and every function call, you can set this + compile_id and it will be used implicitly thereafter. + + + + + + Methods + + assign + + + void assign + mixed var + + + void assign + string varname + mixed var + + + + This is used to assign values to the templates. You can + explicitly pass name/value pairs, or associative arrays + containing the name/value pairs. + + + assign + +// passing name/value pairs +$smarty->assign("Name","Fred"); +$smarty->assign("Address",$address); + +// passing an associative array +$smarty->assign(array("city" => "Lincoln","state" => "Nebraska")); + + + + append + + + void append + mixed var + + + void append + string varname + mixed var + + + + This is used to append data to variables in the template. You + can explicitly pass name/value pairs, or associative arrays + containing the name/value pairs. + + + append + +// passing name/value pairs +$smarty->append("Name","Fred"); +$smarty->append("Address",$address); + +// passing an associative array +$smarty->append(array("city" => "Lincoln","state" => "Nebraska")); + + + + clear_assign + + + void clear_assign + string var + + + + This clears the value of an assigned variable. This + can be a single value, or an array of values. Array + functionality was added to Smarty 1.3.0. + + +clear_assign + +// clear a single variable +$smarty->clear_assign("Name"); + +// clear multiple variables +$smarty->clear_assign(array("Name","Address","Zip")); + + + + clear_all_assign + + + void clear_all_assign + + + + + This clears the values of all assigned variables. + + +clear_all_assign + +// clear all assigned variables +$smarty->clear_all_assign(); + + + + clear_cache + + + void clear_cache + string template + string cache id + + + + This clears the cache for the specified template. If you have + multiple caches for this template, you can clear a specific + cache by supplying the cache id as the second parameter. See the + caching section for more + information. This was added to Smarty 1.3.0. + + +clear_cache + +// clear the cache for a template +$smarty->clear_cache("index.tpl"); + +// clear the cache for a particular cache id in an multiple-cache template +$smarty->clear_cache("index.tpl","CACHEID"); + + + + clear_all_cache + + + void clear_all_cache + + + + + This clears the entire template cache. This was added to Smarty + 1.3.0. + + +clear_all_cache + +// clear the entire cache +$smarty->clear_all_cache(); + + + + clear_compiled_tpl + + + void clear_compiled_tpl + string tpl_file + + + + This clears the compiled version of the specified template + resource, or all compiled template files if one is not specified. + This function is for advanced use only, not normally needed. + + +clear_compiled_tpl + +// clear a specific template resource +$smarty->clear_compiled_tpl("index.tpl"); + +// clear entire compile directory +$smarty->clear_compiled_tpl(); + + + + register_function + + + void register_function + string name + string impl + + + + Use this to dynamically register template function plugins. + Pass in the template function name, followed by the PHP + function name that implements it. + + +register_function + +$smarty->register_function("date_now", "print_current_date"); + +function print_current_date ($params) { + extract($params); + if(empty($format)) + $format="%b %e, %Y"; + echo strftime($format,time()); +} + +// now you can use this in Smarty to print the current date: {date_now} +// or, {date_now format="%Y/%m/%d"} to format it. + + + + unregister_function + + + void unregister_function + string name + + + + Use this to dynamically unregister template function plugin. + Pass in the template function name. + + +unregister_function + +// we don't want template designers to have access to system files + +$smarty->unregister_function("fetch"); + + + + register_modifier + + + void register_modifier + string name + string impl + + + + Use this to dynamically register modifier plugin. Pass in the + template modifier name, followed by the PHP function that it + implements it. + + +register_modifier + +// let's map PHP's stripslashes function to a Smarty modifier. + +$smarty->register_modifier("sslash","stripslashes"); + +// now you can use {$var|sslash} to strip slashes from variables + + + + unregister_modifier + + + void unregister_modifier + string name + + + + Use this to dynamically unregister modifier plugin. Pass in the + template modifier name. + + +unregister_modifier + +// we don't want template designers to strip tags from elements + +$smarty->unregister_modifier("strip_tags"); + + + + register_resource + + + void register_resource + string name + array resource_funcs + + + + Use this to dynamically register a resource plugin with Smarty. + Pass in the name of the resource and the array of PHP functions + implementing it. See + template resources + for more information on how to setup a function for fetching + templates. + + +register_resource + +$smarty->register_resource("db", array("db_get_template", + "db_get_timestamp", + "db_get_secure", + "db_get_trusted")); + + + + unregister_resource + + + void unregister_resource + string name + + + + Use this to dynamically unregister a resource plugin. Pass in the + name of the resource. + + +unregister_resource + +$smarty->unregister_resource("db"); + + + + register_prefilter + + + void register_prefilter + string function_name + + + + Use this to dynamically register prefilters to run templates + through before they are compiled. See template prefilters for + more information on how to setup a prefiltering function. + + + + unregister_prefilter + + + void unregister_prefilter + string function_name + + + + Use this to dynamically unregister a prefilter. + + + + register_postfilter + + + void register_postfilter + string function_name + + + + Use this to dynamically register postfilters to run templates + through after they are compiled. See template postfilters for + more information on how to setup a postfiltering function. + + + + unregister_postfilter + + + void unregister_postfilter + string function_name + + + + Use this to dynamically unregister a postfilter. + + + + register_compiler_function + + + void register_compiler_function + string name + string impl + + + + Use this to dynamically register a compiler function plugin. + Pass in the compiler function name, followed by the PHP + function that implements it. + + + + unregister_compiler_function + + + void unregister_compiler_function + string name + + + + Use this to dynamically unregister a compiler function. Pass in + the name of the compiler function. + + + + trigger_error + + + void trigger_error + string error_msg + [int level] + + + + This function can be used to output an error message using Smarty. + level parameter can be one of the values + used for trigger_error() PHP function, i.e. E_USER_NOTICE, + E_USER_WARNING, etc. By default it's E_USER_WARNING. This function + was added to Smarty 2.0. + + + + + is_cached + + + void is_cached + string template + [string cache_id] + + + + This returns true if there is a valid cache for this template. + This only works if caching is set to true. This + was added to Smarty 1.3.0. + + +is_cached + +$smarty->caching = true; + +if(!$smarty->is_cached("index.tpl")) { + // do database calls, assign vars here +} + +$smarty->display("index.tpl"); + + + You can also pass a cache id as an an optional second parameter + in case you want multiple caches for the given template. + + +is_cached with multiple-cache template + +$smarty->caching = true; + +if(!$smarty->is_cached("index.tpl","FrontPage")) { + // do database calls, assign vars here +} + +$smarty->display("index.tpl","FrontPage"); + + + + get_template_vars + + + array get_template_vars + + + + + This gets an array of the currently assigned template vars. + + +get_template_vars + +// get all assigned template vars +$tpl_vars = $smarty->get_template_vars(); + +// take a look at them +var_dump($tpl_vars); + + + + display + + + void display + string template + string cache id + string compile id + + + + This displays the template. Supply a valid template resource + type and path. As an optional second parameter, you can pass a + cache id. See the caching + section for more information. + + + As an optional third parameter, you can pass a compile id. This + is in the event that you want to compile different versions of + the same template, such as having separate templates compiled + for different languages. This was added to Smarty 1.4.5. + + +display + +include("Smarty.class.php"); +$smarty = new Smarty; +$smarty->caching = true; + +// only do db calls if cache doesn't exist +if(!$smarty->is_cached("index.tpl")) +{ + + // dummy up some data + $address = "245 N 50th"; + $db_data = array( + "City" => "Lincoln", + "State" => "Nebraska", + "Zip" = > "68502" + ); + + $smarty->assign("Name","Fred"); + $smarty->assign("Address",$address); + $smarty->assign($db_data); + +} + +// display the output +$smarty->display("index.tpl"); + + + Use the syntax for template resources to + display files outside of the $template_dir directory. + + +function display template resource examples + +// absolute filepath +$smarty->display("/usr/local/include/templates/header.tpl"); + +// absolute filepath (same thing) +$smarty->display("file:/usr/local/include/templates/header.tpl"); + +// windows absolute filepath (MUST use "file:" prefix) +$smarty->display("file:C:/www/pub/templates/header.tpl"); + +// include from template resource named "db" +$smarty->display("db:header.tpl"); + + + + + fetch + + + string fetch + string template + [string cache_id] + [string compile_id] + + + + This returns the template output instead of displaying it. + Supply a valid template resource + type and path. As an optional second parameter, you can pass a + cache id. See the caching + section for more information. + + + As an optional third parameter, you can pass a compile id. This + is in the event that you want to compile different versions of + the same template, such as having separate templates compiled + for different languages. This was added to Smarty 1.4.5. + + +fetch + +include("Smarty.class.php"); +$smarty = new Smarty; + +$smarty->caching = true; + +// only do db calls if cache doesn't exist +if(!$smarty->is_cached("index.tpl")) +{ + + // dummy up some data + $address = "245 N 50th"; + $db_data = array( + "City" => "Lincoln", + "State" => "Nebraska", + "Zip" = > "68502" + ); + + $smarty->assign("Name","Fred"); + $smarty->assign("Address",$address); + $smarty->assign($db_data); + +} + +// capture the output +$output = $smarty->fetch("index.tpl"); + +// do something with $output here + +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 + + 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 + + Plugin files and functions must follow a very specific naming + convention in order to be located by Smarty. + + + The plugin files must be named as follows: +
+ + + type.name.php + + +
+
+ + Where type is one of these plugin types: + + function + modifier + compiler + prefilter + postfilter + resource + insert + + + + And name should be a valid identifier (letters, + numbers, and underscores only). + + + Some examples: function.html_select_date.php, + resource.db.php, + modifier.spacify.php. + + + The plugin functions inside the plugin files must be named as follows: +
+ + smarty_type_name + +
+
+ + The meanings of type and name are + the same as before. + + + Smarty will output appropriate error messages if the plugin file it + needs is not found, or if the file or the plugin function are named + improperly. + + + + Note that pre/postfilters still have to be correctly named even though + the names are not used for anything except their order of execution. + + +
+ + + Writing Plugins + + Plugins can be either loaded by Smarty automatically from the + filesystem or they can be registered at runtime via one of the + register_* API functions. They can also be unregistered by using + unregister_* API functions. + + + For the plugins that are registered at runtime, the name of the plugin + function(s) does not have to follow the naming convention. + + + If a plugin depends on some functionality provided by another plugin + (as is the case with some plugins bundled with Smarty), then the proper + way to load the needed plugin is this: + + +require_once SMARTY_DIR . 'plugins/function.html_options.php'; + + As a general rule, Smarty object is always passed to the plugins as the last + parameter (except for modifiers). + + + + Template Functions + + + void smarty_function_name + array $params + object &$smarty + + + + All attributes passed to template functions from the template are + contained in the $params as an associative + array. Either access those values directly, e.g. + $params['start'] or use + extract($params) to import them into the symbol + table. + + + The output of the function will be substituted in place of the + function tag in the template (fetch function, for + example). Alternatively, the function can simply perform some other + task without any output (assign function). + + + If the function needs to assign some variables to the template or use + some other Smarty-provided functionality, it can use the supplied + $smarty object to do so. + + + See also: + register_function(), + unregister_function(). + + + + function plugin with output + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: function.eightball.php + * Type: function + * Name: eightball + * Purpose: outputs a random magic answer + * ------------------------------------------------------------- + */ +function smarty_function_eightball($params, &$smarty) +{ + $answers = array('Yes', + 'No', + 'No way', + 'Outlook no so good', + 'Ask again soon', + 'Maybe in your reality'); + + $result = array_rand($answers); + echo $answers[$result]; +} +?> + + + + which can be used in the template as: + + +Question: Will we ever have time travel? +Answer: {eightball}. + + + function plugin without output + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: function.assign.php + * Type: function + * Name: assign + * Purpose: assign a value to a template variable + * ------------------------------------------------------------- + */ +function smarty_function_assign($params, &$smarty) +{ + extract($params); + + if (empty($var)) { + $smarty->trigger_error("assign: missing 'var' parameter"); + return; + } + + if (!in_array('value', array_keys($params))) { + $smarty->trigger_error("assign: missing 'value' parameter"); + return; + } + + $smarty->assign($var, $value); +} +?> + + + + + Modifiers + + Modifiers are little functions that are applied to a variable in the + template before it is displayed or used in some other context. + Modifiers can be chained together. + + + + mixed smarty_modifier_name + mixed $value + [mixed $param1, ...] + + + + The first parameter to the modifier plugin is the value on which + the modifier is supposed to operate. The rest of the parameters can be + optional, depending on what kind of operation is supposed to be + performed. + + + The modifier has to return the result of its processing. + + + See also + register_modifier(), + unregister_modifier(). + + + simple modifier plugin + + This plugin basically aliases one of the built-in PHP functions. It + does not have any additional parameters. + + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: modifier.capitalize.php + * Type: modifier + * Name: capitalize + * Purpose: capitalize words in the string + * ------------------------------------------------------------- + */ +function smarty_modifier_capitalize($string) +{ + return ucwords($string); +} +?> + + + + more complex modifier plugin + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: modifier.truncate.php + * Type: modifier + * Name: truncate + * Purpose: Truncate a string to a certain length if necessary, + * optionally splitting in the middle of a word, and + * appending the $etc string. + * ------------------------------------------------------------- + */ +function smarty_modifier_truncate($string, $length = 80, $etc = '...', + $break_words = false) +{ + if ($length == 0) + return ''; + + if (strlen($string) > $length) { + $length -= strlen($etc); + $fragment = substr($string, 0, $length+1); + if ($break_words) + $fragment = substr($fragment, 0, -1); + else + $fragment = preg_replace('/\s+(\S+)?$/', '', $fragment); + return $fragment.$etc; + } else + return $string; +} +?> + + + + Compiler Functions + + Compiler functions are called only during compilation of the template. + They are useful for injecting PHP code or time-sensitive static + content into the template. If there is both a compiler function and a + custom function registered under the same name, the compiler function + has precedence. + + + + mixed smarty_compiler_name + string $tag_arg + object &$smarty + + + + The compiler function is passed two parameters: the tag argument + string - basically, everything from the function name until the ending + delimiter, and the Smarty object. It's supposed to return the PHP code + to be injected into the compiled template. + + + See also + register_compiler_function(), + unregister_compiler_function(). + + + simple compiler function + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: compiler.tplheader.php + * Type: compiler + * Name: tplheader + * Purpose: Output header containing the source file name and + * the time it was compiled. + * ------------------------------------------------------------- + */ +function smarty_compiler_tplheader($tag_arg, &$smarty) +{ + return "\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';"; +} +?> + + This function can be called from the template as: + + +{* this function gets executed at compile time only *} +{tplheader} + + The resulting PHP code in the compiled template would be something like this: + + +<php +echo 'index.tpl compiled at 2002-02-20 20:02'; +?> + + + + Prefilters/Postfilters + + Prefilter and postfilter plugins are very similar in concept; where + they differ is in the execution -- more precisely the time of their + execution. + + + + string smarty_prefilter_name + string $source + object &$smarty + + + + Prefilters are used to process the source of the template immediately + before compilation. The first parameter to the prefilter function is + the template source, possibly modified by some other prefilters. The + plugin is supposed to return the modified source. Note that this + source is not saved anywhere, it is only used for compilation. + + + + string smarty_postfilter_name + string $compiled + object &$smarty + + + + Postfilters are used to process the compiled output of the template + (the PHP code) immediately after the compilation is done but before the + compiled template is saved to the filesystem. The first parameter to + the postfilter function is the compiled template code, possibly + modified by other postfilters. The plugin is supposed to return the + modified version of this code. + + + prefilter plugin + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: prefilter.pre01.php + * Type: prefilter + * Name: pre01 + * Purpose: Convert html tags to be lowercase. + * ------------------------------------------------------------- + */ + function smarty_prefilter_pre01($source, &$smarty) + { + return preg_replace('!<(\w+)[^>]+>!e', 'strtolower("$1")', $source); + } +?> + + + + postfilter plugin + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: postfilter.post01.php + * Type: postfilter + * Name: post01 + * Purpose: Output code that lists all current template vars. + * ------------------------------------------------------------- + */ + function smarty_postfilter_post01($compiled, &$smarty) + { + $compiled = "<pre>\n<?php print_r(\$this->get_template_vars()); ?>\n</pre>" . $compiled; + return $compiled; + } +?> + + + + Resources + + Resource plugins are meant as a generic way of providing template + sources or PHP script components to Smarty. Some examples of resources: + databases, LDAP, shared memory, sockets, and so on. + + + + There are a total of 4 functions that need to be registered for each + type of resource. Every function will receive the requested resource as + the first parameter and the Smarty object as the last parameter. The + rest of parameters depend on the function. + + + + + bool smarty_resource_name_source + string $rsrc_name + string &$source + object &$smarty + + + bool smarty_resource_name_timestamp + string $rsrc_name + int &$timestamp + object &$smarty + + + bool smarty_resource_name_secure + string $rsrc_name + object &$smarty + + + bool smarty_resource_name_trusted + string $rsrc_name + object &$smarty + + + + + The first function is supposed to retrieve the resource. Its second + parameter is a variable passed by reference where the result should be + stored. The function is supposed to return true if + it was able to successfully retrieve the resource and + false otherwise. + + + + The second function is supposed to retrieve the last modification time + of the requested resource (as a UNIX timestamp). The second parameter + is a variable passed by reference where the timestamp should be stored. + The function is supposed to return true if the + timestamp could be succesfully determined, and false + otherwise. + + + + The third function is supposed to return true or + false, depending on whether the requested resource + is secure or not. This function is used only for template resources but + should still be defined. + + + + The fourth function is supposed to return true or + false, depending on whether the requested resource + is trusted or not. This function is used for only for PHP script + components requested by {include_php} tag or + {insert} tag with src + attribute. However, it should still be defined even for template + resources. + + + See also + register_resource(), + unregister_resource(). + + + resource plugin + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: resource.db.php + * Type: resource + * Name: db + * Purpose: Fetches templates from a database + * ------------------------------------------------------------- + */ +function smarty_resource_db_source($tpl_name, &$tpl_source, &$smarty) +{ + // 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 smarty_resource_db_timestamp($tpl_name, &$tpl_timestamp, &$smarty) +{ + // 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 smarty_resource_db_secure($tpl_name, &$smarty) +{ + // assume all templates are secure + return true; +} + +function smarty_resource_db_trusted($tpl_name, &$smarty) +{ + // not used for templates +} +?> + + + + Inserts + + Insert plugins are used to implement functions that are invoked by + {insert} + tags in the template. + + + + string smarty_insert_name + array $params + object &$smarty + + + + The first parameter to the function is an associative array of + attributes passed to the insert. Either access those values directly, + e.g. $params['start'] or use + extract($params) to import them into the symbol + table. + + + The insert function is supposed to return the result which will be + substituted in place of the {insert} tag in the + template. + + + insert plugin + +<?php +/* + * Smarty plugin + * ------------------------------------------------------------- + * File: insert.time.php + * Type: time + * Name: time + * Purpose: Inserts current date/time according to format + * ------------------------------------------------------------- + */ +function smarty_insert_time($params, &$smarty) +{ + if (empty($params['format'])) { + $smarty->trigger_error("insert time: missing 'format' parameter"); + return; + } + + $datetime = strftime($params['format']); + return $datetime; +} +?> + + +
+ + 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'; + + + + + +