### PHP setup for date_format examples Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-date-format Assigns date format configurations and a timestamp for yesterday to Smarty variables. ```php assign('config', $config); $smarty->assign('yesterday', strtotime('-1 day')); ?> ``` -------------------------------- ### Install Smarty with Composer (Development Version) Source: https://smarty-php.github.io/smarty/4.x/getting-started Use this command to install the latest, unreleased version of Smarty from the master branch. ```bash composer require smarty/smarty:dev-master ``` -------------------------------- ### Example Configuration File Source: https://smarty-php.github.io/smarty/4.x/designers/language-variables/language-config-variables Defines various variables that can be loaded into Smarty templates. ```smarty pageTitle = "This is mine" bodyBgColor = '#eeeeee' tableBorderSize = 3 tableBgColor = "#bbbbbb" rowBgColor = "#cccccc" ``` -------------------------------- ### Looping with start, step, and max attributes Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-section Demonstrates using 'start', 'step', and 'max' attributes to control the {section} loop's behavior and output. ```smarty {section name=foo start=10 loop=20 step=2} {$smarty.section.foo.index} {/section}
{section name=bar loop=21 max=6 step=-2} {$smarty.section.bar.index} {/section} ``` -------------------------------- ### Install Smarty with Composer (Smarty 3) Source: https://smarty-php.github.io/smarty/4.x/getting-started Use this command to install the previous stable version of Smarty, version 3. ```bash composer require smarty/smarty:^3 ``` -------------------------------- ### testInstall() Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions Checks the Smarty installation to verify its integrity. ```APIDOC ## testInstall() ### Description Checks Smarty installation. ### Method Not specified (assumed to be a method call on a Smarty object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $smarty->testInstall(); ``` ### Response None explicitly documented. Likely returns a status or boolean indicating success/failure. ``` -------------------------------- ### Install Smarty with Composer (Latest Stable) Source: https://smarty-php.github.io/smarty/4.x/getting-started Use this command to install the latest stable version of Smarty using Composer. ```bash composer require smarty/smarty ``` -------------------------------- ### Example Output of {html_image} Source: https://smarty-php.github.io/smarty/4.x/designers/language-custom-functions/language-function-html-image Illustrates the generated HTML img tags for various {html_image} function calls. ```html ``` -------------------------------- ### Verify Smarty Installation and Permissions Source: https://smarty-php.github.io/smarty/4.x/getting-started Use the testInstall() method to check if Smarty can access and write to its required directories. ```php $smarty = new Smarty(); $smarty->setTemplateDir('/some/template/dir'); $smarty->setConfigDir('/some/config/dir'); $smarty->setCompileDir('/some/compile/dir'); $smarty->setCacheDir('/some/cache/dir'); $smarty->testInstall(); ``` -------------------------------- ### Output of strip modifier examples Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-strip Shows the resulting output for the template examples, illustrating the effect of the strip modifier with default and custom replacements. ```text Grandmother of eight makes hole in one. Grandmother of eight makes hole in one. Grandmother of eight makes hole in one. ``` -------------------------------- ### Basic Smarty Template Example Source: https://smarty-php.github.io/smarty/4.x/designers/language-basic-syntax A simple Smarty template demonstrating variable output and a foreach loop with a fallback. ```smarty

{$title|escape}

``` -------------------------------- ### Add multiple config directories with keys Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-add-config-dir Add multiple directories for configuration files simultaneously, each with its own specified key. Note: The example uses addTemplateDir, but the principle applies to addConfigDir for config directories. ```php addTemplateDir(array( 'two' => './config_2', 'three' => './config_3', )); ?> ``` -------------------------------- ### Initialize and Increment Counter Source: https://smarty-php.github.io/smarty/4.x/designers/language-custom-functions/language-function-counter This example demonstrates initializing a counter to 0, skipping by 2, and then incrementing it multiple times. The output shows the sequential values generated by the counter. ```smarty {* initialize the count *} {counter start=0 skip=2}
{counter}
{counter}
{counter}
``` -------------------------------- ### Basic Smarty Template Example Source: https://smarty-php.github.io/smarty/4.x/getting-started A simple Smarty template file (`.tpl`) that displays a variable. The initial comment is a convention for syntax highlighting. ```smarty {* Smarty *} Hello {$name}, welcome to Smarty! ``` -------------------------------- ### Basic Smarty Instance Creation Source: https://smarty-php.github.io/smarty/4.x/getting-started This snippet shows the fundamental way to create a new Smarty instance in your PHP script after installation. ```php setConfigDir(array( 'one' => './config', 'two' => './config_2', 'three' => './config_3', )); // get all directories where config files are stored $config_dir = $smarty->getConfigDir(); var_dump($config_dir); // array // get directory identified by key $config_dir = $smarty->getConfigDir('one'); var_dump($config_dir); // string ?> ``` -------------------------------- ### MySQL CacheResource Implementation Source: https://smarty-php.github.io/smarty/4.x/programmers/caching/caching-custom This example demonstrates a custom cache resource implementation using MySQL as the storage backend. It extends `Smarty_CacheResource_Custom` and includes methods for fetching and saving cached content. Ensure the `output_cache` table is created with the provided schema. ```php caching_type = 'mysql'; /** * MySQL CacheResource * * CacheResource Implementation based on the Custom API to use * MySQL as the storage resource for Smarty's output caching. * * Table definition: *
CREATE TABLE IF NOT EXISTS `output_cache` (
 *   `id` CHAR(40) NOT NULL COMMENT 'sha1 hash',
 *   `name` VARCHAR(250) NOT NULL,
 *   `cache_id` VARCHAR(250) NULL DEFAULT NULL,
 *   `compile_id` VARCHAR(250) NULL DEFAULT NULL,
 *   `modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 *   `content` LONGTEXT NOT NULL,
 *   PRIMARY KEY (`id`),
 *   INDEX(`name`),
 *   INDEX(`cache_id`),
 *   INDEX(`compile_id`),
 *   INDEX(`modified`)
 * ) ENGINE = InnoDB;
* * @package CacheResource-examples * @author Rodney Rehm */ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom { // PDO instance protected $db; protected $fetch; protected $fetchTimestamp; protected $save; public function __construct() { try { $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty"); } catch (PDOException $e) { throw new SmartyException('Mysql Resource failed: ' . $e->getMessage()); } $this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id'); $this->fetchTimestamp = $this->db->prepare('SELECT modified FROM output_cache WHERE id = :id'); $this->save = $this->db->prepare('REPLACE INTO output_cache (id, name, cache_id, compile_id, content) VALUES (:id, :name, :cache_id, :compile_id, :content)'); } /** * fetch cached content and its modification time from data source * * @param string $id unique cache content identifier * @param string $name template name * @param string $cache_id cache id * @param string $compile_id compile id * @param string $content cached content * @param integer $mtime cache modification timestamp (epoch) * @return void */ protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime) { $this->fetch->execute(array('id' => $id)); $row = $this->fetch->fetch(); $this->fetch->closeCursor(); if ($row) { $content = $row['content']; $mtime = strtotime($row['modified']); } else { $content = null; $mtime = null; } } /** * Fetch cached content's modification timestamp from data source * * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the complete cached content. * @param string $id unique cache content identifier * @param string $name template name * @param string $cache_id cache id * @param string $compile_id compile id * @return integer|boolean timestamp (epoch) the template was modified, or false if not found */ protected function fetchTimestamp($id, $name, $cache_id, $compile_id) { $this->fetchTimestamp->execute(array('id' => $id)); $mtime = strtotime($this->fetchTimestamp->fetchColumn()); $this->fetchTimestamp->closeCursor(); return $mtime; } ``` -------------------------------- ### Include and Assign to Variable Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-include This example assigns the content of 'nav.tpl' to the '$navbar' variable for later output. ```smarty {include 'nav.tpl' assign=navbar} {include 'header.tpl' title='Smarty is cool'} {$navbar} {* body of template goes here *} {$navbar} {include 'footer.tpl'} ``` -------------------------------- ### Setting and Getting Template Directories Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-get-template-dir This snippet demonstrates how to set multiple template directories using `setTemplateDir()` and then retrieve them either as a full array or by a specific key using `getTemplateDir()`. ```php setTemplateDir(array( 'one' => './templates', 'two' => './templates_2', 'three' => './templates_3', )); // get all directories where templates are stored $template_dir = $smarty->getTemplateDir(); var_dump($template_dir); // array // get directory identified by key $template_dir = $smarty->getTemplateDir('one'); var_dump($template_dir); // string ?> ``` -------------------------------- ### Using fetch() for Email Content Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-fetch This example demonstrates how to use fetch() to generate the body of an email by rendering a Smarty template. The rendered content is then passed to the PHP mail() function. ```php assign('contact_info',$contact_info); $smarty->assign('login_url',"http://{$_SERVER['SERVER_NAME']}/login"); mail($contact_info['email'], 'Thank You', $smarty->fetch('email_body.tpl')); ?> ``` -------------------------------- ### Use Extended Smarty Class Source: https://smarty-php.github.io/smarty/4.x/getting-started Instantiate and use the custom `Smarty_GuestBook` class instead of the base `Smarty` class for simplified setup. ```php assign('name', 'Ned'); $smarty->display('index.tpl'); ``` -------------------------------- ### Smarty examples using date_format with $smarty.now and variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-date-format Shows various ways to use the date_format modifier with the current time and pre-assigned variables, demonstrating different format specifiers. ```smarty {$smarty.now|date_format} {$smarty.now|date_format:"%D"} {$smarty.now|date_format:$config.date} {$yesterday|date_format} {$yesterday|date_format:"%A, %B %e, %Y"} {$yesterday|date_format:$config.time} ``` -------------------------------- ### Basic Function Usage in Smarty Source: https://smarty-php.github.io/smarty/4.x/designers/language-basic-syntax/language-syntax-functions Demonstrates the syntax for invoking built-in and custom functions with attributes in Smarty templates. Includes examples of config loading, template inclusion, and conditional rendering. ```smarty {config_load file="colors.conf"} ``` ```smarty {include file="header.tpl"} ``` ```smarty {insert file="banner_ads.tpl" title="My Site"} ``` ```smarty {if $logged_in} Welcome, {$name}! {else} hi, {$name} {/if} ``` ```smarty {include file="footer.tpl"} ``` -------------------------------- ### MySQL Resource Plugin Example Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-custom This class implements a custom resource plugin for Smarty to use MySQL as a storage resource. It includes table definitions and demo data for setting up the database. Ensure you have a MySQL database with the specified table and user credentials. ```php CREATE TABLE IF NOT EXISTS `templates` ( * `name` varchar(100) NOT NULL, * `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, * `source` text, * PRIMARY KEY (`name`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8; * * Demo data: *
INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');
* * @package Resource-examples * @author Rodney Rehm */ class Smarty_Resource_Mysql extends Smarty_Resource_Custom { // PDO instance protected $db; // prepared fetch() statement protected $fetch; // prepared fetchTimestamp() statement protected $mtime; public function __construct() { try { $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty"); } catch (PDOException $e) { throw new SmartyException('Mysql Resource failed: ' . $e->getMessage()); } $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name'); $this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name'); } /** * Fetch a template and its modification time from database * * @param string $name template name * @param string $source template source * @param integer $mtime template modification timestamp (epoch) * @return void */ protected function fetch($name, &$source, &$mtime) { $this->fetch->execute(array('name' => $name)); $row = $this->fetch->fetch(); $this->fetch->closeCursor(); if ($row) { $source = $row['source']; $mtime = strtotime($row['modified']); } else { $source = null; $mtime = null; } } /** * Fetch a template's modification time from database * * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source. * @param string $name template name * @return integer timestamp (epoch) the template was modified */ protected function fetchTimestamp($name) { $this->mtime->execute(array('name' => $name)); $mtime = $this->mtime->fetchColumn(); $this->mtime->closeCursor(); return strtotime($mtime); } } require_once 'libs/Smarty.class.php'; $smarty = new Smarty(); $smarty->registerResource('mysql', new Smarty_Resource_Mysql()); // using resource from php script $smarty->display("mysql:index.tpl"); ?> ``` -------------------------------- ### Include dynamic content with fallback Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-template-exists This example demonstrates how to dynamically include a template based on user input (`$_GET['page']`). If the requested template does not exist, it falls back to a 'page_not_found.tpl'. ```html {$title} {include file='page_top.tpl'} {* include middle content page *} {include file=$content_template} {include file='page_footer.tpl'} ``` ```php templateExists($mid_template) ){ $mid_template = 'page_not_found.tpl'; } $smarty->assign('content_template', $mid_template); $smarty->display('page_container.tpl'); ?> ``` -------------------------------- ### Template examples with strip modifier Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-strip Demonstrates the output of a variable with no modifier, with the strip modifier (single space), and with the strip modifier using a custom replacement string (' '). ```smarty {$articleTitle} {$articleTitle|strip} {$articleTitle|strip:' '} ``` -------------------------------- ### MySQL Custom Resource Plugin Example Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-resources This PHP class demonstrates how to create a custom resource plugin for Smarty that fetches templates from a MySQL database. It includes table creation and demo data SQL. ```php CREATE TABLE IF NOT EXISTS `templates` ( * `name` varchar(100) NOT NULL, * `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, * `source` text, * PRIMARY KEY (`name`) * ) ENGINE=InnoDB DEFAULT CHARSET=utf8; * * Demo data: *
INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{"x}');
* * @package Resource-examples * @author Rodney Rehm */ class Smarty_Resource_Mysql extends Smarty_Resource_Custom { // PDO instance protected $db; // prepared fetch() statement protected $fetch; // prepared fetchTimestamp() statement protected $mtime; public function __construct() { try { $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty"); } catch (PDOException $e) { throw new SmartyException('Mysql Resource failed: ' . $e->getMessage()); } $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name'); $this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name'); } /** * Fetch a template and its modification time from database * * @param string $name template name * @param string $source template source * @param integer $mtime template modification timestamp (epoch) * @return void */ protected function fetch($name, &$source, &$mtime) { $this->fetch->execute(array('name' => $name)); $row = $this->fetch->fetch(); $this->fetch->closeCursor(); if ($row) { $source = $row['source']; $mtime = strtotime($row['modified']); } else { $source = null; $mtime = null; } } /** * Fetch a template's modification time from database * * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source. * @param string $name template name * @return integer timestamp (epoch) the template was modified */ protected function fetchTimestamp($name) { $this->mtime->execute(array('name' => $name)); $mtime = $this->mtime->fetchColumn(); $this->mtime->closeCursor(); return strtotime($mtime); } } require_once 'libs/Smarty.class.php'; $smarty = new Smarty(); $smarty->registerResource('mysql', new Smarty_Resource_Mysql()); // using resource from php script $smarty->display("mysql:index.tpl"); ?> ``` -------------------------------- ### Get Smarty Plugins Directories Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-get-plugins-dir This snippet demonstrates how to set multiple plugin directories and then retrieve them using getPluginsDir(). It's useful for verifying the plugin paths configured for your Smarty instance. ```php setPluginsDir(array( './plugins', './plugins_2', )); // get all directories where plugins are stored $config_dir = $smarty->getPluginsDir(); var_dump($config_dir); // array ?> ``` -------------------------------- ### Smarty Eightball Function Example Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-functions This function outputs a random magic answer when called from a Smarty template. It requires no special setup beyond defining the function. ```php ``` ```smarty Question: Will we ever have time travel? Answer: {eightball}. ``` -------------------------------- ### View and chain template directory configurations Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-add-template-dir Demonstrates how to view the current list of template directories using getTemplateDir() and how to chain multiple configuration methods, including setTemplateDir() and addTemplateDir(), for fluent interface usage. ```php getTemplateDir()); // chaining of method calls $smarty->setTemplateDir('./templates') ->addTemplateDir('./templates_1', 'one') ->addTemplateDir('./templates_2', 'two'); ?> ``` -------------------------------- ### HTML Date Select with Relative Years Source: https://smarty-php.github.io/smarty/4.x/designers/language-custom-functions/language-function-html-select-date This example demonstrates how to set the start and end years for the date selection relative to the current year using `start_year` and `end_year` attributes. `display_days` is set to false to omit the day selection. ```smarty {* start and end year can be relative to current year *} {html_select_date prefix='StartDate' time=$time start_year='-5' end_year='+1' display_days=false} ``` ```html ``` -------------------------------- ### Assigning variables for escape examples Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-escape PHP code to assign variables that will be used in Smarty template examples for the escape modifier. ```php assign('articleTitle', "'Stiff Opposition Expected to Casketless Funeral Plan'"); $smarty->assign('EmailAddress','smarty@example.com'); ?> ``` -------------------------------- ### Example Postfilter Plugin Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-prefilters-postfilters This postfilter plugin prepends code to list all current template variables within `
` tags to the compiled output. It processes the compiled template code after compilation but before saving.

```php
\ngetTemplateVars()); ?>\n
" . $compiled; return $compiled; } ?> ``` -------------------------------- ### Fetch Banner Content with {insert} Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-insert Use the {insert} tag to dynamically fetch content like banners that should not be cached. This example shows both the standard and shorthand syntax for calling an insert function named 'getBanner' with parameters. ```smarty {* example of fetching a banner *} {insert name="getBanner" lid=#banner_location_id# sid=#site_id#} {insert "getBanner" lid=#banner_location_id# sid=#site_id#} {* short-hand *} ``` -------------------------------- ### Assigning loop start and end variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-for This PHP code assigns values to 'start' and 'to' variables for use in a Smarty {for} loop. ```php assign('start',10); $smarty->assign('to',5); ``` -------------------------------- ### compileAllConfig() Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions Compiles all known configuration files. ```APIDOC ## compileAllConfig() ### Description Compiles all known config files. ### Method Not specified (assumed to be a method call on a Smarty object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $smarty->compileAllConfig(); ``` ### Response None explicitly documented. ``` -------------------------------- ### Chaining addPluginsDir() and setPluginsDir() calls Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-add-plugins-dir Demonstrates chaining multiple method calls for setting and adding plugin directories in a fluent interface. ```php setPluginsDir('./plugins') ->addPluginsDir('./plugins_1') ->addPluginsDir('./plugins_2'); ?> ``` -------------------------------- ### {for} loop with {forelse} for no iteration Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-for This {for} loop is set up to iterate from '$start' to '$to'. Since '$start' (10) is greater than '$to' (5), the loop will not execute, and the {forelse} block will be rendered. ```smarty ``` -------------------------------- ### Lowercase Modifier Example Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-lower Shows how to use the lower modifier to convert a Smarty variable to lowercase in a template. This example includes the PHP code to assign a variable and the corresponding Smarty template. ```php assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.'); ?> ``` ```smarty {$articleTitle} {$articleTitle|lower} ``` -------------------------------- ### Get Registered Object Reference Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-get-registered-object This snippet demonstrates how to get a reference to a registered object within a custom Smarty block function. Ensure the object name is passed via the 'object' parameter. ```php getRegisteredObject($params['object']); // use $obj_ref is now a reference to the object } } ?> ``` -------------------------------- ### Smarty Block Function Example: translate Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-block-functions This is an example of a Smarty block function named 'translate'. It demonstrates how to process content within a block, specifically for translation. The function is designed to only perform its core logic on the closing tag. ```php ``` -------------------------------- ### Chaining Smarty Configuration Methods Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-set-config-dir Demonstrates method chaining for setting multiple Smarty directories in a single statement. This improves code readability and conciseness. ```php setTemplateDir('./templates') ->setConfigDir('./config') ->setCompileDir('./templates_c') ->setCacheDir('./cache'); ?> ``` -------------------------------- ### Using Windows Filepaths with File Resource Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-file Illustrates how to correctly specify Windows file paths, including drive letters, when using the 'file:' template resource to avoid namespace conflicts. ```php display('file:C:/export/templates/index.tpl'); $smarty->display('file:F:/path/to/my/templates/menu.tpl'); ?> ``` -------------------------------- ### Basic Usage of count_characters Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-count-characters Use the count_characters modifier to get the length of a string variable in a Smarty template. ```Smarty {$myVar|count_characters} ``` -------------------------------- ### Template Using $smarty.config Syntax for Config Variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-variables/language-config-variables Demonstrates referencing configuration variables using the `$smarty.config.variable` syntax after loading a config file. ```smarty {config_load file='foo.conf'} {$smarty.config.pageTitle}
First Last Address
``` -------------------------------- ### Template Using #hash# Syntax for Config Variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-variables/language-config-variables Demonstrates referencing configuration variables using the `#variable#` syntax after loading a config file. ```smarty {config_load file='foo.conf'} {#pageTitle#}
First Last Address
``` -------------------------------- ### PHP assignment for truncate example Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-truncate Assigns a long string to a Smarty variable to be used with the truncate modifier in the template. ```php assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.'); ?> ``` -------------------------------- ### Assigning a long string for wordwrap examples Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-wordwrap Assigns a sample article title to a Smarty variable for demonstration purposes. ```PHP assign('articleTitle', "Blind woman gets new kidney from dad she hasn't seen in years." ); ?> ``` -------------------------------- ### Assigning Variables and Using {assign} Source: https://smarty-php.github.io/smarty/4.x/designers/language-basic-syntax/language-syntax-variables Demonstrates how to assign values to variables using the {assign} tag, including simple assignments and assignments with expressions. ```smarty {assign var=foo value='baa'}{$foo} <-- displays "baa", see {assign} ``` -------------------------------- ### Add a config directory with a specific key Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-add-config-dir Add a directory for configuration files and assign it a specific key for later reference or management. ```php addConfigDir('./config_1', 'one'); ?> ``` -------------------------------- ### Get Smarty Cache Directory Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-get-cache-dir Retrieve the directory where compiled templates are stored. See also `setCacheDir()` and `$cache_dir`. ```php getCacheDir(); ?> ``` -------------------------------- ### Basic count_words usage Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-count-words Apply the count_words modifier directly to a Smarty variable in a template to get the word count. ```smarty {$myVar|count_words} ``` -------------------------------- ### PHP Variable Assignment for Template Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-indent This PHP code assigns a multi-line string to a Smarty variable, which will be used in the template examples. ```PHP assign('articleTitle', 'NJ judge to rule on nude beach. Sun or rain expected today, dark tonight. Statistics show that teen pregnancy drops off significantly after 25.' ); ?> ``` -------------------------------- ### Compile All Config Files Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-compile-all-config This snippet demonstrates how to compile all configuration files with a specific extension and forces recompilation of all files, regardless of modification status. Ensure the Smarty.class.php is included and a Smarty instance is created. ```php compileAllConfig('.config',true); ?> ``` -------------------------------- ### Loading a Configuration File Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-config-load Loads variables from the specified configuration file into the template's local context. This is the standard way to include configuration settings. ```smarty {config_load file="example.conf"} ``` ```smarty {config_load "example.conf"} {* short-hand *} ``` -------------------------------- ### Count Characters with Whitespace Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-count-characters This example demonstrates how to count characters including whitespace by passing 'true' as a parameter to the count_characters modifier. ```PHP assign('articleTitle', 'Cold Wave Linked to Temperatures.'); ?> ``` ```Smarty {$articleTitle} {$articleTitle|count_characters} {$articleTitle|count_characters:true} ``` ```text Cold Wave Linked to Temperatures. 29 33 ``` -------------------------------- ### Programmatic Template Inheritance with Extends Resource Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-extends Demonstrates how to use the 'extends:' resource to define inheritance chains for templates directly from PHP scripts. This includes inheriting from multiple template sources and different resource types. ```php display('extends:parent.tpl|child.tpl|grandchild.tpl'); // inheritance from multiple template sources $smarty->display('extends:db:parent.tpl|file:child.tpl|grandchild.tpl|eval:{block name="fooBazVar_"}hello world{/block}'); ?> ``` -------------------------------- ### PHP Array Assignment for Smarty Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-section Assigns a range of integers to a Smarty variable named 'arr'. This is a prerequisite for the subsequent Smarty template examples. ```php assign('arr', $id); ?> ``` -------------------------------- ### Absolute and Resource Path Includes Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-include Shows how to include templates using absolute file paths, the 'file:' prefix, and custom template resources like 'db:'. ```smarty {* 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 a $variable template - eg $module = 'contacts' *} {include file="$module.tpl"} {* wont work as its single quotes ie no variable substitution *} {include file='$module.tpl'} {* include a multi $variable template - eg amber/links.view.tpl *} {include file="$style_dir/$module.$view.tpl"} ``` -------------------------------- ### Example of Upper Modifier with PHP Assignment Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-upper Shows how to assign a string to a Smarty variable in PHP and then display it in both its original and uppercase forms in the template. ```php assign('articleTitle', "If Strike isn't Settled Quickly it may Last a While."); ?> ``` ```smarty {$articleTitle} {$articleTitle|upper} ``` ```text If Strike isn't Settled Quickly it may Last a While. IF STRIKE ISN'T SETTLED QUICKLY IT MAY LAST A WHILE. ``` -------------------------------- ### Indenting with Custom Number of Spaces Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-indent This example shows how to use the indent modifier to indent a string with a custom number of spaces (10 in this case). ```Smarty {$articleTitle|indent:10} ``` -------------------------------- ### Radio button output example Source: https://smarty-php.github.io/smarty/4.x/designers/language-custom-functions/language-function-html-radios This is the resulting HTML output for the {html_radios} function when using either the 'values'/'output' or 'options' attributes with a selected value. ```html



``` -------------------------------- ### Default File Template Access Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-file Demonstrates the default way to display a template using the 'file:' resource, which is equivalent to omitting the resource type if it's the default. ```php display('index.tpl'); $smarty->display('file:index.tpl'); // same as above ?> ``` -------------------------------- ### Get Compiled Template Directory Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-get-compile-dir Retrieves the directory path where Smarty stores compiled template files. This is useful for debugging or verifying the configuration. ```php getCompileDir(); ?> ``` -------------------------------- ### Loading Smarty Filters Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-load-filter Demonstrates how to load 'pre' and 'output' filters using the loadFilter() method. Ensure the filter plugins are available in Smarty's plugin paths. ```php loadFilter('pre', 'trim'); // load another prefilter named 'datefooter' $smarty->loadFilter('pre', 'datefooter'); // load output filter named 'compress' $smarty->loadFilter('output', 'compress'); ?> ``` -------------------------------- ### Config File with Repeated Variables Source: https://smarty-php.github.io/smarty/4.x/programmers/api-variables/variable-config-overwrite Example of a Smarty configuration file where a variable is listed multiple times to store an array of data when `$config_overwrite` is FALSE. ```smarty # row colors rowColors = #FF0000 rowColors = #00FF00 rowColors = #0000FF ``` -------------------------------- ### Abort foreach loop with break Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-foreach The {break} statement allows you to terminate a {foreach} loop prematurely. This example stops the loop when a specific condition is met. ```smarty {$data = [1,2,3,4,5]} {foreach $data as $value} {if $value == 3} {* abort iterating the array *} {break} {/if} {$value} {/foreach} {* prints: 1 2 *} ``` -------------------------------- ### configLoad() Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions Loads configuration file data and assigns it to the template. ```APIDOC ## configLoad() ### Description Loads config file data and assigns it to the template. ### Method Not specified (assumed to be a method call on a Smarty object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $smarty->configLoad('my_config.conf'); ``` ### Response None explicitly documented. ``` -------------------------------- ### configLoad() Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-config-load Loads configuration file data and assigns it to the template. This function works identically to the template {config_load} function. Assigned template variables are kept across invocations of fetch() and display(). Config vars loaded from configLoad() are always global in scope. Config files are also compiled for faster execution, and respect the $force_compile and $compile_check settings. ```APIDOC ## configLoad() ### Description Loads config file data and assigns it to the template. ### Method ``` void configLoad(string file, [string section]) ``` ### Parameters #### Path Parameters - **file** (string) - Required - The configuration file to load. - **section** (string) - Optional - The specific section within the configuration file to load. ### Request Example ```php // load config variables and assign them $smarty->configLoad('my.conf'); // load a section $smarty->configLoad('my.conf', 'foobar'); ``` ### See Also - `{config_load}` - `getConfigVars()` - `clearConfig()` - `config variables` ``` -------------------------------- ### Smarty Compiler Function Example Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-compiler-functions Defines a Smarty compiler function that outputs the source file name and compilation time. This function is executed only during the compilation phase. ```php _current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>"; } ?> ``` -------------------------------- ### Using Static Values Source: https://smarty-php.github.io/smarty/4.x/designers/language-basic-syntax/language-syntax-variables Illustrates that static string values can be used directly where variables are expected. ```smarty {"foo"} <-- static values are allowed ``` -------------------------------- ### Registering a Prefilter to Remove HTML Comments Source: https://smarty-php.github.io/smarty/4.x/programmers/advanced-features/advanced-features-prefilters This example demonstrates how to define a PHP function that removes HTML comments from template source and then register it as a prefilter with Smarty. ```php /U",'',$tpl_source); } // register the prefilter $smarty->registerFilter('pre','remove_dw_comments'); $smarty->display('index.tpl'); ?> ``` -------------------------------- ### Accessing Templates from Specific Template Directories Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-file Illustrates how to use bracket syntax to specify templates from particular directories within `$template_dir`, including numeric and string index access. ```php setTemplateDir(array( './templates', // element: 0, index: 0 './templates_2', // element: 1, index: 1 '10' => 'templates_10', // element: 2, index: '10' 'foo' => 'templates_foo', // element: 3, index: 'foo' )); /* assume the template structure ./templates/foo.tpl ./templates_2/foo.tpl ./templates_2/bar.tpl ./templates_10/foo.tpl ./templates_10/bar.tpl ./templates_foo/foo.tpl */ // regular access $smarty->display('file:foo.tpl'); // will load ./templates/foo.tpl // using numeric index $smarty->display('file:[1]foo.tpl'); // will load ./templates_2/foo.tpl // using numeric string index $smarty->display('file:[10]foo.tpl'); // will load ./templates_10/foo.tpl // using string index $smarty->display('file:[foo]foo.tpl'); // will load ./templates_foo/foo.tpl // using "unknown" numeric index (using element number) $smarty->display('file:[2]foo.tpl'); // will load ./templates_10/foo.tpl ?> ``` -------------------------------- ### {for} loop with 'max' attribute Source: https://smarty-php.github.io/smarty/4.x/designers/language-builtin-functions/language-function-for This {for} loop iterates from a variable 'foo' starting at 3 up to the 'to' variable, but is limited to a maximum of 3 iterations using the 'max' attribute. ```smarty ``` -------------------------------- ### Smarty Assign Function Example Source: https://smarty-php.github.io/smarty/4.x/programmers/plugins/plugins-functions This function assigns a value to a template variable. It requires 'var' and 'value' parameters to be passed from the template. It will trigger an error if these parameters are missing. ```php assign($params['var'], $params['value']); } ?> ``` -------------------------------- ### Fetch File via FTP with Variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-custom-functions/language-function-fetch Fetch a file from an FTP server using Smarty variables for credentials, server, and path. ```smarty {fetch file="ftp://`$user`:`$password`@`$server`/`$path`"} ``` -------------------------------- ### Register a MySQL Resource Handler Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-register-resource Dynamically registers a custom resource handler named 'mysql' with Smarty. This example assumes a `Smarty_Resource_Mysql` class is available and extends `Smarty_Resource`. ```php registerResource('mysql', new Smarty_Resource_Mysql()); ?> ``` -------------------------------- ### Accessing Configuration and Server Variables Source: https://smarty-php.github.io/smarty/4.x/designers/language-basic-syntax/language-syntax-variables Shows how to access variables defined in Smarty configuration files using hash syntax or the smarty.config object, and how to access server variables. ```smarty {#foo#} <-- display the config file variable "foo" {$smarty.config.foo} <-- synonym for {#foo#} ``` ```smarty {* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*} {$smarty.server.SERVER_NAME} ``` -------------------------------- ### Chaining method calls for configuration Source: https://smarty-php.github.io/smarty/4.x/programmers/api-functions/api-add-config-dir Demonstrates chaining multiple Smarty configuration methods, including setting the initial config directory and adding subsequent ones with keys, in a single statement. ```php setConfigDir('./config') ->addConfigDir('./config_1', 'one') ->addConfigDir('./config_2', 'two'); ?> ``` -------------------------------- ### count_words modifier example with PHP assignment Source: https://smarty-php.github.io/smarty/4.x/designers/language-modifiers/language-modifier-count-words Demonstrates assigning a string to a Smarty variable and then using the count_words modifier in the template to display both the original string and its word count. ```php assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.'); ?> ``` ```smarty {$articleTitle} {$articleTitle|count_words} ``` ```text Dealers Will Hear Car Talk at Noon. 7 ``` -------------------------------- ### Accessing Templates from Any Directory Source: https://smarty-php.github.io/smarty/4.x/programmers/resources/resources-file Demonstrates how to access templates located outside of `$template_dir` by providing an absolute path prefixed with 'file:'. ```php display('file:/export/templates/index.tpl'); $smarty->display('file:/path/to/my/templates/menu.tpl'); ?> ```