### Verify Smarty Installation and Directory Setup
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Use the testInstall() method to check if your Smarty directories are correctly configured and have the necessary permissions.
```php
setTemplateDir('/some/template/dir');
$smarty->setConfigDir('/some/config/dir');
$smarty->setCompileDir('/some/compile/dir');
$smarty->setCacheDir('/some/cache/dir');
$smarty->testInstall();
```
--------------------------------
### Example lang.en.ini Config File
Source: https://smarty-php.github.io/smarty/5.x/api/variables/config-files
An example INI-style configuration file demonstrating global variables, sections, and multi-line values.
```ini
# global variables
pageTitle = "Main Menu"
[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."""
```
--------------------------------
### Example Configuration File
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-config-load
This is an example of a Smarty configuration file (`.conf`) containing global variables and a specific section for customer variables.
```smarty-config
#this is config file comment
# global variables
pageTitle = "Main Menu"
bodyBgColor = #000000
tableBgColor = #000000
rowBgColor = #00ff00
#customer variables section
[Customer]
pageTitle = "Customer Info"
```
--------------------------------
### PHP setup for date_format examples
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-date-format
This PHP code sets up Smarty variables, including date formatting configurations and a timestamp for yesterday, to be used in Smarty templates.
```php
assign('config', $config);
$smarty->assign('yesterday', strtotime('-1 day'));
?>
```
--------------------------------
### Example Configuration File
Source: https://smarty-php.github.io/smarty/5.x/designers/language-variables/language-config-variables
Defines variables that can be loaded into Smarty templates.
```smarty
pageTitle = "This is mine"
bodyBgColor = '#eeeeee'
tableBorderSize = 3
tableBgColor = "#bbbbbb"
rowBgColor = "#cccccc"
```
--------------------------------
### Install Smarty with Composer (Development Version)
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Install the latest, unreleased development version of Smarty using Composer.
```bash
composer require smarty/smarty:dev-master
```
--------------------------------
### testInstall()
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-test-install
Verifies that all required working folders of the Smarty installation can be accessed. It outputs a corresponding protocol.
```APIDOC
## testInstall()
### Description
Verifies that all required working folders of the Smarty installation can be accessed. It outputs a corresponding protocol.
### Method
```php
void
```
### Function Signature
```php
testInstall()
```
### Usage Example
```php
testInstall();
?>
```
```
--------------------------------
### Install Smarty with Composer (Version 4)
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Install the previous stable version, Smarty 4, using Composer.
```bash
composer require smarty/smarty:^4
```
--------------------------------
### Install Smarty with Composer (Latest Stable)
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Use this command to install the latest stable version of Smarty using Composer.
```bash
composer require smarty/smarty
```
--------------------------------
### Using Section Iteration and Index
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-section
Shows how to use the `iteration` and `index` properties within a section loop. The `iteration` property starts at one, while `index` starts at zero or a specified `start` value.
```php
$id = range(3000,3015);
$smarty->assign('arr', $id);
```
```smarty
{section name=cu loop=$arr start=5 step=2}
iteration={$smarty.section.cu.iteration}
index={$smarty.section.cu.index}
id={$custid[cu]}
{/section}
```
--------------------------------
### Smarty Template Tags Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax/language-syntax-tags
Demonstrates the basic syntax for Smarty tags, including loading configuration, including other templates, and conditional logic.
```smarty
{config_load file="colors.conf"}
{include file="header.tpl"}
{if $logged_in}
Welcome, {$name}!
{else}
hi, {$name}
{/if}
{include file="footer.tpl"}
```
--------------------------------
### HTML Options Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax/language-syntax-attributes
Shows how to populate a select dropdown using the `html_options` function with an array of options and a pre-selected value.
```smarty
```
--------------------------------
### Practical Regex Validation Examples
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax/language-syntax-operators
Provides practical examples of using the `matches` operator for common validation tasks such as email, password strength, URL, and numeric input validation.
```smarty
{if $email matches "/^[^@\s]+@[^@\s]+\.[^@\s]+$/"}
Valid email address
{else}
Please enter a valid email address
{/if}
{if $password matches "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/"}
Strong password
{else}
Password must contain uppercase, lowercase, numbers and be at least 8 characters
{/if}
{if $url matches "/^https?:\/\/(www\.)?[a-z0-9\-]+\.[a-z]{2,}\)+/i"}
Valid URL format
{else}
Please enter a valid URL
{/if}
{if $input matches "/^[0-9]+$/"}
Valid numeric input
{else}
Please enter numbers only
{/if}
```
--------------------------------
### Basic Smarty Template Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax
A simple Smarty template demonstrating variable output and a foreach loop with a fallback.
```smarty
{$title|escape}
{foreach $cities as $city}
{$city.name|escape} ({$city.population})
{foreachelse}
no cities found
{/foreach}
```
--------------------------------
### Instantiate Smarty via Composer or Directly
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Demonstrates how to create a new Smarty instance, either after installing with Composer or by including the Smarty class file directly.
```php
{$title|escape}
The number of pixels is: {math equation="x * y" x=$height y=$width}.
{if $email matches "/^[^@]+@[^@]+\.[^@]+$/"}
Valid email address
{else}
Please enter a valid email
{/if}
```
--------------------------------
### Iterating with start, step, and max attributes
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-section
Demonstrates using 'start', 'step', and 'max' attributes in the {section} function for custom iteration ranges.
```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}
```
--------------------------------
### Explicitly load a template using the 'file' resource
Source: https://smarty-php.github.io/smarty/5.x/api/resources
This example explicitly uses the 'file:' resource type to load 'homepage.tpl', demonstrating the default resource behavior.
```php
display('file:homepage.tpl');
```
--------------------------------
### Complete Example with Backed Enums (PHP 8.1+)
Source: https://smarty-php.github.io/smarty/5.x/designers/language-variables/language-assigned-variables
Demonstrates assigning a backed enum from PHP and accessing its properties in a Smarty template. Requires PHP 8.1+.
```php
assign('currentStatus', Status::Active);
$smarty->display('template.tpl');
```
```smarty
{* Display enum properties *}
Current status: {$currentStatus->name} (value: {$currentStatus->value})
{* Use in HTML attributes *}
```
--------------------------------
### Smarty Template Indentation Examples
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-indent
Demonstrates various ways to use the indent modifier with different parameters.
```smarty
{$articleTitle}
{$articleTitle|indent}
{$articleTitle|indent:10}
{$articleTitle|indent:1:"\t"}
```
--------------------------------
### Verify Smarty Installation
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-test-install
This function verifies that all required working folders of the Smarty installation can be accessed. It does output a corresponding protocol.
```php
testInstall();
?>
```
--------------------------------
### Fetch or Display Templates Directly
Source: https://smarty-php.github.io/smarty/5.x/api/rendering
Use `display()` to render a template to standard output or `fetch()` to get the output as a string. Both methods accept simple filenames for template loading.
```php
display('homepage.tpl');
// or
$output = $smarty->fetch('homepage.tpl');
```
--------------------------------
### PHP Setup for {html_checkboxes} with options
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-html-checkboxes
Prepare an associative array where keys are values and values are the output labels for the checkboxes. Assign this to a Smarty variable.
```php
assign(
'cust_checkboxes',
[
1000 => 'Joe Schmoe',
1001 => 'Jack Smith',
1002 => 'Jane Johnson',
1003 => 'Charlie Brown',
]
);
$smarty->assign('customer_id', 1001);
?>
```
--------------------------------
### Example Smarty Config File Syntax
Source: https://smarty-php.github.io/smarty/5.x/designers/config-files
This snippet demonstrates the basic syntax for Smarty configuration files, including global variables, sections, multi-line values, and comments. Values can be quoted or unquoted, and multi-line values must use triple quotes.
```smarty-config
# 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.example.com
db=ADDRESSBOOK
user=php-user
pass=foobar
```
--------------------------------
### PHP Setup for {html_checkboxes} with values/output
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-html-checkboxes
Prepare arrays for checkbox values and their corresponding output labels in PHP. Assign these to Smarty variables for use in the template.
```php
assign('cust_ids', array(1000,1001,1002,1003));
$smarty->assign('cust_names', array(
'Joe Schmoe',
'Jack Smith',
'Jane Johnson',
'Charlie Brown')
);
$smarty->assign('customer_id', 1001);
?>
```
--------------------------------
### Instantiate Security Class
Source: https://smarty-php.github.io/smarty/5.x/api/security
Create an instance of the \Smarty\Security class and modify its properties to customize the security policy. This example disables access to constants.
```php
allow_constants = false;
$smarty->enableSecurity($my_security_policy);
?>
```
--------------------------------
### Final Rendered HTML Example
Source: https://smarty-php.github.io/smarty/5.x
Illustrates the final HTML output when a Smarty template is processed with given variable assignments.
```html
Hello world
The number of pixels is: 307200.
```
--------------------------------
### Base Template Example
Source: https://smarty-php.github.io/smarty/5.x/api/inheritance
Define a base template with named blocks that can be overridden by child templates. This serves as the foundation for your template structure.
```smarty
{block name=title}Default Page Title{/block}
{block name=head}{/block}
{block name=body}{/block}
```
--------------------------------
### Basic {while} loop in Smarty
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-while
This example demonstrates a basic {while} loop that counts down a variable until it reaches 1. Ensure the variable is initialized before the loop.
```smarty
{while $foo > 0}
{$foo--}
{/while}
```
--------------------------------
### Smarty Template Example
Source: https://smarty-php.github.io/smarty/5.x/getting-started
A basic Smarty template file (`.tpl`) that displays a variable with HTML escaping.
```smarty
{* Smarty *}
Hello {$name|escape}, welcome to Smarty!
```
--------------------------------
### Using a Runtime Tag in a Template
Source: https://smarty-php.github.io/smarty/5.x/api/extending/tags
Example of how to use a registered runtime tag within a Smarty template.
```smarty
{* This is a comment *}
Question: Will we ever have time travel?
Answer: {eightball}.
```
--------------------------------
### Grandchild Template Example
Source: https://smarty-php.github.io/smarty/5.x/api/inheritance
Demonstrates a grandchild template that extends a child template, further overriding blocks. This showcases the depth of inheritance possible.
```smarty
{extends file='myproject.tpl'}
{block name=title}My Page Title{/block}
{block name=head}
{/block}
{block name=body}My HTML Page Body goes here{/block}
```
--------------------------------
### Truncate modifier examples
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-truncate
Illustrates various ways to use the truncate modifier with different parameters, including length, replacement string, and boundary options.
```php
assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
?>
```
```smarty
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}
{$articleTitle|truncate:30:'..':true:true}
```
--------------------------------
### PHP Database Query for {html_checkboxes} Options
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-html-checkboxes
Fetch data from a database to populate checkbox options. This example retrieves contact types and a specific contact's details.
```php
assign('contact_types',$db->getAssoc($sql));
$sql = 'select contact_id, contact_type_id, contact '
.'from contacts where contact_id=12';
$smarty->assign('contact',$db->getRow($sql));
?>
```
--------------------------------
### Looping with Section Properties
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-section
Illustrates using various section properties like index, index_prev, and index_next to display data in a table. This example shows how to access current, previous, and next item details within a loop.
```php
$data = [1001,1002,1003,1004,1005];
$smarty->assign('rows',$data);
```
```smarty
{* $rows[row.index] and $rows[row] are identical in meaning *}
table>
index
id
index_prev
prev_id
index_next
next_id
{section name=row loop=$rows}
{$smarty.section.row.index}
{$rows[row]}
{$smarty.section.row.index_prev}
{$rows[row.index_prev]}
{$smarty.section.row.index_next}
{$smarty.section.row.index_next}
{/section}
```
--------------------------------
### Using fetch() for Email Content
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-fetch
This example illustrates how to use the fetch() function to generate the body of an email using a Smarty template. The rendered template output is then passed to PHP's 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'));
?>
```
--------------------------------
### Formatted Output with Sprintf
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-math
Applies a format specifier using sprintf syntax to control the output of a mathematical result. This example formats a floating-point sum to two decimal places.
```smarty
{* you can supply a format parameter in sprintf format *}
{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}
```
--------------------------------
### HTML Select Date Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax/language-syntax-attributes
Example of using the `html_select_date` function with a boolean attribute.
```smarty
{html_select_date display_days=true}
```
--------------------------------
### Assigning Variable for Indentation Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-indent
Assign a multi-line string to a Smarty variable. This variable 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.'
);
```
--------------------------------
### Extend Smarty Class for Environment Setup
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Define a custom class that extends Smarty to centralize environment configuration. This includes setting template, compile, config, and cache directories, along with HTML escaping and caching preferences.
```php
setTemplateDir('/web/www.example.com/guestbook/templates/');
$this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$this->setConfigDir('/web/www.example.com/guestbook/configs/');
$this->setCacheDir('/web/www.example.com/guestbook/cache/');
$this->setEscapeHtml(true);
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
}
```
--------------------------------
### Define and Call a Template Function with {call}
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-call
This example demonstrates defining a recursive template function 'menu' using {function} and then calling it using {call} with data. The {call} tag is essential when the function is defined externally or when the compiler needs to resolve the function call in a single pass. The shorthand {call menu ...} is also shown.
```smarty
{* define the function *}
{function name=menu level=0}
{/function}
{* create an array to demonstrate *}
{$menu = ['item1','item2','item3' => ['item3-1','item3-2','item3-3' =>
['item3-3-1','item3-3-2']],'item4']}
{* run the array through the function *}
{call name=menu data=$menu}
{call menu data=$menu} {* short-hand *}
```
--------------------------------
### Configure template directories and access templates by index
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Demonstrates setting multiple template directories with named and numeric indices, and accessing templates using bracket-syntax for specific directories.
```php
setTemplateDir([
'./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
```
--------------------------------
### Assigning loop start and end variables
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-for
Assigns variables 'start' and 'to' for use in a {for} loop, including a {forelse} condition.
```php
assign('start',10);
$smarty->assign('to',5);
?>
```
--------------------------------
### Using the {strip} tag
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-strip
This example demonstrates how to use the {strip} tag to format HTML content within a Smarty template. Whitespace and carriage returns within the tag are removed before output.
```smarty
{* the following will be all run into one line upon output *}
{strip}
{/strip}
```
--------------------------------
### Define and Nest Template Instance Filters
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-setfilter
This example demonstrates how to use the {setfilter} tag to apply filters to variables within a template block, including nesting filters and applying modifiers with parameters. Filters defined within an inner {setfilter} block replace the outer block's filters for the enclosed content.
```smarty
```
--------------------------------
### Handle Windows file paths for templates
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Illustrates how to correctly specify Windows file paths for templates using the 'file:' resource type, including drive letters.
```php
display('file:C:/export/templates/index.tpl');
$smarty->display('file:F:/path/to/my/templates/menu.tpl');
```
--------------------------------
### Set Custom Extension List
Source: https://smarty-php.github.io/smarty/5.x/api/extending/extensions
This example demonstrates how to completely override the default extension list with a custom set, including core and default extensions. This allows for precise control over the available Smarty functionality.
```php
setExtensions([
new Smarty\Extension\CoreExtension(),
new MyCustomExtension(),
new Smarty\Extension\DefaultExtension(),
]);
```
--------------------------------
### Registering and Using an Email Protection Output Filter
Source: https://smarty-php.github.io/smarty/5.x/api/filters/output-filters
This example demonstrates how to register a custom output filter to protect email addresses from spambots by encoding them. The filter function `protect_email` uses a regular expression to find and replace '@' symbols with '%40'.
```php
registerFilter("output", "protect_email");
$smarty->display("index.tpl');
```
--------------------------------
### Get string length with strlen
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-strlen
Use the strlen modifier to get the length of a string or a number. It counts all characters, including spaces.
```smarty
{"Smarty"|strlen} # renders: 6
{156|strlen} # renders: 3
```
--------------------------------
### Accessing Section Index
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-section
Demonstrates how to access the current index of a section loop. The `index` property starts at zero or a specified `start` value and increments by `step`.
```smarty
{section name=customer loop=$custid}
{$smarty.section.customer.index} id: {$custid[customer]}
{/section}
```
--------------------------------
### Smarty Syntax Error Example
Source: https://smarty-php.github.io/smarty/5.x/appendixes/troubleshooting
This is an example of a Smarty syntax error, such as an unknown tag or missing section name. Smarty will report the template name and line number where the error occurred.
```text
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
```
--------------------------------
### PHP Parse Error Example
Source: https://smarty-php.github.io/smarty/5.x/appendixes/troubleshooting
This is an example of a PHP parse error, often caused by missing closing tags in Smarty templates. The error line number refers to the compiled PHP script.
```php
Parse error: parse error in /path/to/smarty/templates_c/index.tpl.php on line 75
```
--------------------------------
### Including Templates Using Different Resource Types
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-include
Demonstrates various ways to specify template locations, including absolute file paths, Windows paths with the 'file:' prefix, custom resource types like 'db:', and variable-based template names.
```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"}
```
--------------------------------
### Replace modifier examples with PHP assignment
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-replace
This example demonstrates how to use the `replace` modifier in a Smarty template after assigning a variable using PHP. It shows replacing a specific word and replacing spaces with multiple spaces.
```php
assign('articleTitle', "Child's Stool Great for Use in Garden.");
?>
```
```smarty
{$articleTitle}
{$articleTitle|replace:'Garden':'Vineyard'}
{$articleTitle|replace:' ':' '}
```
--------------------------------
### Get Assigned Template Variable Values
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-get-template-vars
Use `getTemplateVars()` to retrieve a specific assigned variable by name, or call it without arguments to get all assigned variables. This is useful for inspecting or reusing variable values within your PHP code.
```php
getTemplateVars('foo');
// get all assigned template vars
$all_tpl_vars = $smarty->getTemplateVars();
// take a look at them
print_r($all_tpl_vars);
?>
```
--------------------------------
### Load templates using absolute paths
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Demonstrates loading templates from outside the configured template directories by providing an absolute path prefixed with 'file:'.
```php
display('file:/export/templates/index.tpl');
$smarty->display('file:/path/to/my/templates/menu.tpl');
````
```
--------------------------------
### Template Using $smarty.config Syntax
Source: https://smarty-php.github.io/smarty/5.x/designers/language-variables/language-config-variables
Demonstrates referencing config variables using the `$smarty.config.variable` syntax after loading the config file.
```smarty
{config_load file='foo.conf'}
{$smarty.config.pageTitle}
First
Last
Address
```
--------------------------------
### Template Using #hash_marks# Syntax
Source: https://smarty-php.github.io/smarty/5.x/designers/language-variables/language-config-variables
Demonstrates referencing config variables using the `#variable#` syntax after loading the config file.
```smarty
{config_load file='foo.conf'}
{#pageTitle#}
First
Last
Address
```
--------------------------------
### {for} loop with {forelse}
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-for
A {for} loop that will not iterate because the start value is greater than the end value, triggering the {forelse} block.
```smarty
{for $foo=$start to $to}
{$foo}
{forelse}
no iteration
{/for}
```
--------------------------------
### Load a template file from the filesystem
Source: https://smarty-php.github.io/smarty/5.x/api/resources
This is the most basic way to load a template file named 'homepage.tpl' from the filesystem using Smarty.
```php
display('homepage.tpl');
```
--------------------------------
### Initialize Smarty Instance
Source: https://smarty-php.github.io/smarty/5.x/api/basics
Create a new Smarty object to begin using its features. Ensure you have included the Composer autoloader.
```php
assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
```
```smarty
{$articleTitle}
{$articleTitle|count_words}
```
```text
Dealers Will Hear Car Talk at Noon.
7
```
--------------------------------
### Load Specific Configuration Section
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-config-load
Loads configuration variables from the 'foobar' section of 'my.conf'. This allows for more granular control over which configuration settings are loaded.
```php
configLoad('my.conf', 'foobar');
?>
```
--------------------------------
### Extend Security Class
Source: https://smarty-php.github.io/smarty/5.x/api/security
Extend the \Smarty\Security class to customize security policy settings. This example disables access to constants.
```php
enableSecurity('My_Security_Policy');
?>
```
--------------------------------
### configLoad()
Source: https://smarty-php.github.io/smarty/5.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 configuration file data and assigns it to the template.
### Method
void
### 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`
```
--------------------------------
### Use PHP count Modifier
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers
Illustrates using the PHP 'count' function as a modifier to get the number of elements in an array.
```smarty
{$myArray|@count}
```
--------------------------------
### Fetch File via FTP with Variables
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-fetch
Fetch a file from an FTP server using Smarty variables for credentials and paths.
```smarty
{fetch file="ftp://`$user`:`$password`@`$server`/`$path`"}
```
--------------------------------
### Using String and Eval Resources in PHP
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Demonstrates how to display templates from strings using both the 'string:' resource for compiled reuse and the 'eval:' resource for compilation on every render. Assigns a variable to the template.
```php
assign('foo', 'value');
$template_string = 'display {$foo} here';
$smarty->display('string:' . $template_string); // compiles for later reuse
$smarty->display('eval:' . $template_string); // compiles every time
```
--------------------------------
### Get Template Variables in Smarty
Source: https://smarty-php.github.io/smarty/5.x/upgrading
The `Smarty::getVariable` method has been removed. Use `Smarty::getTemplateVars` instead to retrieve template variables.
```php
Smarty::getTemplateVars
```
--------------------------------
### fetch() method
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-fetch
The fetch() method returns the template output as a string. It accepts the template name and an optional cache ID.
```APIDOC
## fetch()
### Description
Returns the template output as a string.
### Method Signature
`string fetch(string $template, [string $cache_id = null], [string $compile_id = null])`
### Parameters
* **template** (string) - The name or path of the template to fetch.
* **cache_id** (string, optional) - The cache ID to use for retrieving cached content. Defaults to null.
* **compile_id** (string, optional) - The compile ID to use for retrieving compiled content. Defaults to null.
### Request Example
```php
setCaching(true);
// set a separate cache_id for each unique URL
$cache_id = md5($_SERVER['REQUEST_URI']);
// capture the output
$output = $smarty->fetch('index.tpl', $cache_id);
// do something with $output here
echo $output;
?>
```
### Related Methods
See also `{fetch}` `display()`, `{eval}`, and `templateExists()`.
```
--------------------------------
### Config File with Duplicate Variables
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-variables/variable-config-overwrite
Example of a Smarty configuration file where a variable is defined multiple times. When `$config_overwrite` is FALSE, these will be stored as an array.
```smarty
# row colors
rowColors = #FF0000
rowColors = #00FF00
rowColors = #0000FF
```
--------------------------------
### Registering and Using a Custom Stream Resource in PHP
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Demonstrates how to register a custom PHP stream wrapper and then use it as a Smarty template resource in PHP. This allows fetching templates from custom stream sources.
```php
display('myresource:bar.tpl');
```
--------------------------------
### Test Template Existence Before Including
Source: https://smarty-php.github.io/smarty/5.x/api/rendering
Use `templateExists()` to verify if a template file is available before attempting to include it. This prevents errors and allows fallback to a default template if the requested one is not found.
```html
{$title|escape}
{* include middle content page *}
{include file=$content_template}
```
```php
templateExists($mid_template)){
$mid_template = 'page_not_found.tpl';
}
$smarty->assign('content_template', $mid_template);
$smarty->display('page_container.tpl');
```
--------------------------------
### Upper Modifier Example with PHP Assignment
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-upper
Shows how to assign a string to a Smarty variable in PHP and then display it in uppercase within a Smarty 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.
```
--------------------------------
### Set and Add Config Directories
Source: https://smarty-php.github.io/smarty/5.x/api/configuring
Configure Smarty's search paths for configuration files. Use `setConfigDir` for single or multiple paths, `addConfigDir` to append, and `getConfigDir` to retrieve the list of configured directories.
```php
setConfigDir('./config');
// set multiple directories where config files are stored
$smarty->setConfigDir(['./config', './config_2', './config_3']);
// add directory where config files are stored to the current list of dirs
$smarty->addConfigDir('./config_1');
// add multiple directories to the current list of dirs
$smarty->addConfigDir([
'./config_2',
'./config_3',
]);
// chaining of method calls
$smarty->setConfigDir('./config')
->addConfigDir('./config_1', 'one')
->addConfigDir('./config_2', 'two');
// get all directories where config files are stored
$config_dirs = $smarty->getConfigDir();
var_dump($config_dirs); // array
// get directory identified by key
$config_dir = $smarty->getConfigDir(0);
var_dump($config_dir); // string
```
--------------------------------
### Generated HTML Output for {html_checkboxes}
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-html-checkboxes
Example of the HTML output generated by the {html_checkboxes} function, including labels, input elements, and checked status.
```html
```
--------------------------------
### Change Default Resource Type
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Modify the default resource type used by Smarty to load templates. This example sets the default to 'mysql'.
```php
setDefaultResourceType('mysql');
```
--------------------------------
### Output of Appended Array Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-append
This is the expected output generated by the preceding Smarty code that uses the {append} function to build and display an array.
```text
The first name is Bob.
The last name is Meyer.
```
--------------------------------
### Capturing Template Output with fetch()
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-fetch
This snippet demonstrates how to use the fetch() function to capture the rendered output of a template into a variable. It shows setting up Smarty, enabling caching, generating a unique cache ID, and then fetching the template content.
```php
setCaching(true);
// set a separate cache_id for each unique URL
$cache_id = md5($_SERVER['REQUEST_URI']);
// capture the output
$output = $smarty->fetch('index.tpl', $cache_id);
// do something with $output here
echo $output;
?>
```
--------------------------------
### Basic display() usage with caching
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-display
This snippet demonstrates the basic usage of the display() function, including setting up caching and assigning variables to the template before rendering. It shows how to check if a template is cached and only perform database operations if it's not.
```php
setCaching(true);
// only do db calls if cache doesn't exist
if(!$smarty->isCached('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('data', $db_data);
}
// display the output
$smarty->display('index.tpl');
?>
```
--------------------------------
### HTML Comment Example
Source: https://smarty-php.github.io/smarty/5.x/designers/language-basic-syntax/language-syntax-comments
HTML comments are included in the source code sent to the browser. Use them for client-side notes or to comment out HTML elements.
```html
```
```html
```
```html
```
--------------------------------
### Basic Template Inclusion
Source: https://smarty-php.github.io/smarty/5.x/designers/language-builtin-functions/language-function-include
Demonstrates including other templates using the 'include' function. It shows including a fixed file, a file specified by a variable, and using the shortform 'file' attribute.
```smarty
{$title}
{include file='page_header.tpl'}
{* body of template goes here, the $tpl_name variable
is replaced with a value eg 'contact.tpl'
*}
{include file="$tpl_name.tpl"}
{* using shortform file attribute *}
{include 'page_footer.tpl'}
```
```smarty
{include 'links.tpl' title='Newest links' links=$link_array}
{* body of template goes here *}
{include 'footer.tpl' foo='bar'}
```
--------------------------------
### Using a Compiler Tag in a Template
Source: https://smarty-php.github.io/smarty/5.x/api/extending/tags
Example of how to use a registered compiler tag within a Smarty template. This tag is executed only at compile time.
```smarty
{* this function gets executed at compile time only *}
{tplheader}
```
--------------------------------
### Render Template from String
Source: https://smarty-php.github.io/smarty/5.x/api/basics
Display template content directly from a string or fetch it for further processing. The `{$smarty.version}` placeholder shows the current Smarty version.
```php
display('string:The current smarty version is: {$smarty.version}.');
// or
```
```php
echo $smarty->fetch('string:The current smarty version is: {$smarty.version}.');
```
--------------------------------
### Create and Display a Template Object
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-create-template
Instantiates a template object using 'index.tpl', assigns a variable 'foo' to its scope, and then displays the template. This is a common pattern for rendering simple templates.
```php
createTemplate('index.tpl');
// assign variable to template scope
$tpl->assign('foo','bar');
// display the template
$tpl->display();
?>
```
--------------------------------
### Initialize and Increment Counter
Source: https://smarty-php.github.io/smarty/5.x/designers/language-custom-functions/language-function-counter
Demonstrates initializing a counter at 0 with a skip interval of 2, and then calling it multiple times to show the incrementing behavior.
```smarty
{* initialize the count *}
{counter start=0 skip=2}
{counter}
{counter}
{counter}
```
--------------------------------
### Strip modifier with custom replacement
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-strip
You can specify a custom string to replace whitespace characters instead of a single space. This example uses ' ' for HTML.
```smarty
{$articleTitle|strip:' '}
```
--------------------------------
### Load Configuration Variables
Source: https://smarty-php.github.io/smarty/5.x/programmers/api-functions/api-config-load
Loads configuration variables from 'my.conf' and assigns them to the template. This is the basic usage for loading all variables from a configuration file.
```php
configLoad('my.conf');
?>
```
--------------------------------
### Lowercase Modifier Example with PHP Assignment
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-lower
Shows how to assign a string to a Smarty variable in PHP and then use the `lower` modifier in the template to convert it to lowercase.
```php
assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.');
?>
```
```smarty
{$articleTitle}
{$articleTitle|lower}
```
```text
Two Convicts Evade Noose, Jury Hung.
two convicts evade noose, jury hung.
```
--------------------------------
### Set Directory Permissions for Compile and Cache
Source: https://smarty-php.github.io/smarty/5.x/getting-started
Ensures the compile and cache directories are writable by the web server user. Adjust 'nobody:nobody' and paths as needed for your environment.
```bash
chown nobody:nobody /web/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/
```
--------------------------------
### Displaying Inherited Templates in PHP
Source: https://smarty-php.github.io/smarty/5.x/api/resources
Shows how to use the 'extends:' resource in PHP to specify a chain of parent and child templates for inheritance. It supports multiple template sources and mixed 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}');
```
--------------------------------
### Create and Display a Template Object
Source: https://smarty-php.github.io/smarty/5.x/api/rendering
Create a template object using `createTemplate()` for reusable templates. Assign variables specific to this template object before displaying it.
```php
createTemplate('index.tpl');
// assign a variable (available only to this template)
$tpl->assign('title', 'My Homepage!');
// display the template
$tpl->display();
```
--------------------------------
### Basic substr usage
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-substr
Extract a substring starting from a specific offset. If length is omitted, the rest of the string is returned. Supports negative offsets to count from the end of the string.
```smarty
{"Smarty"|substr:2} # renders: arty
```
```smarty
{"Smarty"|substr:2:3} # renders: art
```
```smarty
{"Smarty"|substr:-2} # renders: ty
```
```smarty
{"Smarty"|substr:-2:1} # renders: t
```
--------------------------------
### Join array elements with a hyphen separator
Source: https://smarty-php.github.io/smarty/5.x/designers/language-modifiers/language-modifier-join
Specify a separator string as a parameter to the join modifier to insert it between each array element. This example uses a hyphen to join the elements.
```smarty
{$myArray|join:"-"}
```
--------------------------------
### Assign Variable and Display Template in PHP
Source: https://smarty-php.github.io/smarty/5.x/getting-started
PHP script to instantiate Smarty, configure directories, assign a template variable, and display the specified template file.
```php
setTemplateDir('/web/www.example.com/guestbook/templates/');
$smarty->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
$smarty->setCacheDir('/web/www.example.com/guestbook/cache/');
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
```