diff options
Diffstat (limited to 'docs')
133 files changed, 2186 insertions, 3878 deletions
diff --git a/docs/api/basics.md b/docs/api/basics.md new file mode 100644 index 00000000..0b58c028 --- /dev/null +++ b/docs/api/basics.md @@ -0,0 +1,92 @@ +# Basics + +## Installation +For installation instructies, please see the [getting started section](../getting-started.md). + +## Rendering a template +Here's how you create an instance of Smarty in your PHP scripts: +```php +<?php + +require 'vendor/autoload.php'; +use Smarty\Smarty; +$smarty = new Smarty(); +``` + +You now have a Smarty object that you can use to render templates. + +```php +<?php + +require 'vendor/autoload.php'; +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->display('string:The current smarty version is: {$smarty.version}.'); +// or +echo $smarty->fetch('string:The current smarty version is: {$smarty.version}.'); +``` + +## Using file-based templates +You probably want to manage your templates as files. Create a subdirectory called 'templates' and +then configure Smarty to use that: + +```php +<?php + +require 'vendor/autoload.php'; +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->setTemplateDir(__DIR__ . '/templates'); +``` + +Say you have a template file called 'version.tpl', stored in the 'templates' directory like this: +```smarty +<h1>Hi</h1> +The current smarty version is: {$smarty.version|escape}. +``` + +You can now render this, using: +```php +<?php + +require 'vendor/autoload.php'; +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->setTemplateDir(__DIR__ . '/templates'); +$smarty->display('version.tpl'); +``` + +## Assigning variables + +Templates start to become really useful once you add variables to the mix. + +Create a template called 'footer.tpl' in the 'templates' directory like this: +```smarty +<small>Copyright {$companyName|escape}</small> +``` + +Now assign a value to the 'companyName' variable and render your template like this: + +```php +<?php + +require 'vendor/autoload.php'; +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->setTemplateDir(__DIR__ . '/templates'); +$smarty->assign('companyName', 'AC & ME Corp.'); +$smarty->display('footer.tpl'); +``` + +Run this, and you will see: + +```html +<small>Copyright AC & ME Corp.</small> +``` + +Note how the [escape modifier](../designers/language-modifiers/language-modifier-escape.md) +translated the `&` character into the proper HTML syntax `&`.
\ No newline at end of file diff --git a/docs/api/caching/basics.md b/docs/api/caching/basics.md new file mode 100644 index 00000000..19c04c99 --- /dev/null +++ b/docs/api/caching/basics.md @@ -0,0 +1,184 @@ +# Caching + +Caching is used to speed up the rendering of a template by saving and re-using the output. + +If a cached version of the call is available, that is displayed instead of +regenerating the output. Caching can speed things up tremendously, +especially templates with longer computation times. + +Since templates can include or extend other templates, one +cache file could conceivably be made up of several template files, +config files, etc. + +> ** Note ** +> +> Since templates are dynamic, it is important to be careful what you are +> caching and for how long. For instance, if you are displaying the front +> page of your website that does not change its content very often, it +> might work well to cache this page for an hour or more. On the other +> hand, if you are displaying a page with a timetable containing new +> information by the minute, it would not make sense to cache this page. + +## Setting Up Caching + +The first thing to do is enable caching by calling `Smarty::setCaching()` with either +`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or `\Smarty\Smarty::CACHING_LIFETIME_SAVED`. +Or with `\Smarty\Smarty::CACHING_OFF` to disable caching again. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +// enable caching, using the current lifetime (see below) +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +// enable caching, using the lifetime set when the cache was saved (see below) +$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED); + +// disable caching +$smarty->setCaching(Smarty::CACHING_OFF); + +$smarty->display('index.tpl'); +``` + +With caching enabled, the function call to `$smarty->display('index.tpl')` will +render the template as usual, but also saves a copy of its output. On the +next call to `$smarty->display('index.tpl')`, the cached copy will be used +instead of rendering the template again. + +> **Note** +> +> By default, Smarty saved its caches as files in a dir called `cache` relative to the current +> directory. The default directory can be changed using `$smarty->setCacheDir('/some/cache/dir');` +> The files are named similar +> to the template name. Although they end in the `.php` extension, they +> are not intended to be directly executable. Do not edit these files! + +## Cache lifetime + +Each cached page has a limited lifetime. The default value is 3600 +seconds, or one hour. After that time expires, the cache is regenerated. + +You can change the lifetime as follows: +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); +// or $smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED); + +// set the cache_lifetime to 5 minutes +$smarty->setCacheLifetime(5 * 60); +``` + +Setting caching to a value of `\Smarty\Smarty::CACHING_LIFETIME_CURRENT` tells Smarty to use +the current lifetime to determine if the cache has expired. + +A value of `\Smarty\Smarty::CACHING\_LIFETIME\_SAVED` tells Smarty to use the lifetime value at the time the +cache was generated. This way you can set the just before rendering a template to have granular control over +when that particular cache expires. + +An example: +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +// retain current cache lifetime for each specific display call +$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED); + +// set the cache_lifetime for index.tpl to 5 minutes +$smarty->setCacheLifetime(300); +$smarty->display('index.tpl'); + +// set the cache_lifetime for home.tpl to 1 hour +$smarty->setCacheLifetime(3600); +$smarty->display('home.tpl'); + +// NOTE: the following $cache_lifetime setting will not work when $caching +// is set to Smarty::CACHING_LIFETIME_SAVED. +// The cache lifetime for home.tpl has already been set +// to 1 hour, and will no longer respect the value of $cache_lifetime. +// The home.tpl cache will still expire after 1 hour. +$smarty->setCacheLifetime(30); // 30 seconds +$smarty->display('home.tpl'); +``` + +## Compile check + +By default, every template file and config file that is involved with the cache file +is checked for modification. If any of the files have been modified +since the cache was generated, the cache is immediately regenerated. + +This is a computational overhead, so for optimum performance, disable this on a production environment: + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); +$smarty->setCompileCheck(Smarty::COMPILECHECK_OFF); + +$smarty->display('index.tpl'); +``` + +## Checking if a template is cached + +Smarty's `isCached() method can be used to test if a +template has a valid cache or not. If you have a cached template that +requires something like a database fetch, you can use this to skip that +process. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +if (!$smarty->isCached('index.tpl')) { + // No cache available, do variable assignments here. + $smarty->assign('data', do_expensive_database_calls()); +} + +$smarty->display('index.tpl'); +``` + +## Nocache-blocks +You can keep parts of a page dynamic (disable caching) with the +[`{nocache}{/nocache}`](../../designers/language-builtin-functions/language-function-nocache.md) block function, +or by using the `nocache` parameter for most template functions. + +Let's say the whole page can be cached except for a banner that is +displayed down the side of the page. By using a [`{nocache}{/nocache}`](../../designers/language-builtin-functions/language-function-nocache.md) +block for the banner, you can +keep this element dynamic within the cached content. + +## Clearing the cache +You can clear all the cache files with Smarty's `clearAllCache()` method, or individual cache +files with the `clearCache()` method. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +// clear only cache for index.tpl +$smarty->clearCache('index.tpl'); + +// clear out all cache files +$smarty->clearAllCache(); + +// clear out all cache files older than one hour +$smarty->clearAllCache(3600); + +// or, clear all expired caches +$smarty->clearAllCache(Smarty::CLEAR_EXPIRED); +``` + + diff --git a/docs/api/caching/custom-storage-layers.md b/docs/api/caching/custom-storage-layers.md new file mode 100644 index 00000000..f43e724e --- /dev/null +++ b/docs/api/caching/custom-storage-layers.md @@ -0,0 +1,36 @@ +# Custom cache storage layers + +As an alternative to using the default file-based caching mechanism, you +can specify a custom cache implementation that will be used to read, +write and clear cached files. + +With a custom cache implementation you could replace the slow filesystem by a +faster storage engine, centralize the cache to be accessible to multiple +servers. + +Smarty requires implementations to extend `\Smarty\Cacheresource\Base`, but encourages you to either extend +`\Smarty\Cacheresource\Custom` or `\Smarty\Cacheresource\KeyValueStore`. + +- `\Smarty\Cacheresource\Custom` is a simple API directing all read, write, +clear calls to your implementation. This API allows you to store +wherever and however you deem fit. +- `\Smarty\Cacheresource\KeyValueStore` allows you to turn any +KeyValue-Store (like APC or Memcache) into a full-featured +CacheResource implementation. Everything around deep +cache-groups like "a|b|c" is being handled for you in a way that +guarantees clearing the cache-group "a" will clear all nested groups +as well - even though KeyValue-Stores don't allow this kind of +hierarchy by nature. + +Custom CacheResources must be registered on +runtime with `Smarty\Smarty::setCacheResource()`: + +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->setCacheResource(new My_CacheResource_Mysql()); +``` + diff --git a/docs/api/caching/multiple-caches-per-template.md b/docs/api/caching/multiple-caches-per-template.md new file mode 100644 index 00000000..c3da9d0a --- /dev/null +++ b/docs/api/caching/multiple-caches-per-template.md @@ -0,0 +1,137 @@ +# Multiple caches per template + +## Introduction + +You can have multiple cache files for a single call to +`display()` or `fetch()`. + +Let's say that +a call to `$smarty->display('index.tpl')` may have several different output +contents depending on some condition, and you want separate caches for +each one. You can do this by passing a `$cache_id` as the second +parameter to the function call: + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +$my_cache_id = (int) $_GET['article_id']; + +$smarty->display('index.tpl', $my_cache_id); +``` + + +Above, we are passing the variable `$my_cache_id` to +[`display()`](#api.display) as the `$cache_id`. For each unique value of +`$my_cache_id`, a separate cache will be generated for `index.tpl`. In +this example, `article_id` was passed in the URL and is used as the +`$cache_id`. + +> **Note** +> +> Be very cautious when passing values from a client (web browser) into +> Smarty or any PHP application. Although the above example of using the +> article_id from the URL looks handy, it could have bad consequences. +> The `$cache_id` is used to create a directory on the file system, so +> if the user decided to write a script that sends random article_id's at a rapid pace, +> this could possibly cause problems at the server level. +> Be sure to sanitize any data passed in before using it. In this example, you might want to check if +> the article_id is a valid ID in the database. + +Be sure to pass the same `$cache_id` as the second parameter to +`isCached()` and `clearCache()`. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +$my_cache_id = (int) $_GET['article_id']; + +if (!$smarty->isCached('index.tpl', $my_cache_id)) { + // ... +} + +$smarty->display('index.tpl', $my_cache_id); +``` + +## Clearing specific caches + +You can clear all caches for a particular `$cache_id` by passing NULL as +the first parameter to `clearCache()`. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +// clear all caches with "sports" as the $cache_id +$smarty->clearCache(null, 'sports'); + +$smarty->display('index.tpl', 'sports'); +``` + +In this manner, you can "group" your caches together by giving them the +same `$cache_id`. + +## Advanced cache grouping + +You can do more elaborate grouping by setting up `$cache_id` groups. +This is accomplished by separating each sub-group with a vertical bar +`|` in the `$cache_id` value. You can have as many sub-groups as you +like. + +- You can think of cache groups like a directory hierarchy. For + instance, a cache group of `'a|b|c'` could be thought of as the + directory structure `'/a/b/c/'`. + +- `clearCache(null, 'a|b|c')` would be like removing the files + `'/a/b/c/*'`. `clearCache(null, 'a|b')` would be like removing the + files `'/a/b/*'`. + +- If you specify a template name such as + `clearCache('foo.tpl', 'a|b|c')` then Smarty will attempt to remove + `'/a/b/c/foo.tpl'`. + +- You CANNOT remove a specified template name under multiple cache + groups such as `'/a/b/*/foo.tpl'`, the cache grouping works + left-to-right ONLY. You will need to group your templates under a + single cache group hierarchy to be able to clear them as a group. + +Cache grouping should not be confused with your template directory +hierarchy, the cache grouping has no knowledge of how your templates are +structured. So for example, if you have a template structure like +`themes/blue/index.tpl` and you want to be able to clear all the cache +files for the "blue" theme, you will need to create a cache group +structure that mimics your template file structure, such as +`display('themes/blue/index.tpl', 'themes|blue')`, then clear them with +`clearCache(null, 'themes|blue')`. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); + +// clear all caches with 'sports|basketball' as the first two cache_id groups +$smarty->clearCache(null, 'sports|basketball'); + +// clear all caches with "sports" as the first cache_id group. This would +// include "sports|basketball", or "sports|(anything)|(anything)|(anything)|..." +$smarty->clearCache(null, 'sports'); + +// clear the foo.tpl cache file with "sports|basketball" as the cache_id +$smarty->clearCache('foo.tpl', 'sports|basketball'); + +$smarty->display('index.tpl', 'sports|basketball'); +``` + + diff --git a/docs/api/configuring.md b/docs/api/configuring.md new file mode 100644 index 00000000..32144b39 --- /dev/null +++ b/docs/api/configuring.md @@ -0,0 +1,175 @@ +# Configuring Smarty + +## Setting the template path +By default, Smarty looks for templates to render in `./templates`. + +You can change this, or even use multiple paths to use when looking for templates. + +If you need to change this, you can use `setTemplateDir()` or `addTemplateDir()`. +Use `getTemplateDir()` to retrieve the configured paths. + +```php +<?php + + // set a single directory where the config files are stored +$smarty->setTemplateDir('./config'); + +// set multiple directories where config files are stored +$smarty->setTemplateDir(['./config', './config_2', './config_3']); + +// add directory where config files are stored to the current list of dirs +$smarty->addTemplateDir('./config_1'); + +// add multiple directories to the current list of dirs +$smarty->addTemplateDir([ + './config_2', + './config_3', +]); + +// chaining of method calls +$smarty->setTemplateDir('./config') + ->addTemplateDir('./config_1') + ->addTemplateDir('./config_2'); + +// get all directories where config files are stored +$template_dirs = $smarty->getTemplateDir(); +var_dump($template_dirs); // array + +// get directory identified by key +$template_dir = $smarty->getTemplateDir(0); +var_dump($template_dir); // string +``` + +## Setting the path for compiled templates +Smarty compiles templates to native PHP to be as fast as possible. +The default path where these PHP-files are stored is `./templates_c`. + +If you need to change this, you can use `setCompileDir()`. +Use `getCompileDir()` to retrieve the configured path. + +```php +<?php + +// set another path to store compiled templates +$smarty->setCompileDir('/data/compiled_templates'); + +// get directory where compiled templates are stored +$compileDir = $smarty->getCompileDir(); +``` + + +## Setting the config path +Smarty can [load data from config files](./variables/config-files.md). +By default, Smarty loads the config files from `./configs`. + +You can change this, or even use multiple paths to use when looking for config files. + +If you need to change this, you can use `setConfigDir()` or `addConfigDir()`. +Use `getConfigDir()` to retrieve the configured paths. + +```php +<?php + + // set a single directory where the config files are stored +$smarty->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 +``` + +## Setting the path for caches +Even though Smarty runs templates as native PHP for maximum speed, it still needs to +execute the PHP code on each call. If your data doesn't change all that often, you +may be able to speed up your application even more by using output caching. + +Output caching can be a tricky subject, so we devoted an entire [section to caching](./caching/basics.md). +Be sure to read that if you want to use caching. + +By default, Smarty stores caches to PHP-files in a subdirectory named `./cache`. + +If you need to change this, you can use `setCacheDir()`. +Use `getCacheDir()` to retrieve the configured path. + +```php +<?php + +// set another path to store caches +$smarty->setCacheDir('/data/caches'); + +// get directory where cached templates are stored +$cacheDir = $smarty->getCacheDir(); +``` + +## Disabling compile check +By default, Smarty tests to see if the +current template has changed since the last time +it was compiled. If it has changed, it recompiles that template. + +Once an application is put into production, this compile-check step +is usually no longer needed and the extra checks can significantly hurt performance. +Be sure to disable compile checking on production for maximum performance. +```php +<?php +$smarty->setCompileCheck(\Smarty\Smarty::COMPILECHECK_OFF); +``` + +If [`caching`](./caching/basics.md) is enabled and compile-check is +enabled, then the cache files will get regenerated if an involved +template file or config file was updated. + +## Charset encoding + +There are a variety of encodings for textual data, ISO-8859-1 (Latin1) +and UTF-8 being the most popular. Unless you change `\Smarty\Smarty::$_CHARSET`, +Smarty recognizes `UTF-8` as the internal charset. + +> **Note** +> +> `ISO-8859-1` has been PHP\'s default internal charset since the +> beginning. Unicode has been evolving since 1991. Since then, it has +> become the one charset to conquer them all, as it is capable of +> encoding most of the known characters even across different character +> systems (latin, cyrillic, japanese, ...). `UTF-8` is unicode\'s most +> used encoding, as it allows referencing the thousands of character +> with the smallest size overhead possible. +> +> Since unicode and UTF-8 are very widespread nowadays, their use is +> strongly encouraged. + +> **Note** +> +> Smarty\'s internals and core plugins are truly UTF-8 compatible since +> Smarty 3.1. + +```php +<?php + +// use japanese character encoding +mb_internal_charset('EUC-JP'); + +\Smarty\Smarty::$_CHARSET = 'EUC-JP'; +$smarty = new \Smarty\Smarty(); +``` + diff --git a/docs/api/extending/block-tags.md b/docs/api/extending/block-tags.md new file mode 100644 index 00000000..2ae6e77b --- /dev/null +++ b/docs/api/extending/block-tags.md @@ -0,0 +1,59 @@ +# Custom block tags + +Block tags are tags of the form: `{func} .. {/func}`. In other +words, they enclose a template block and operate on the contents of this +block. + +Block functions take precedence over normal tags of the same name, that is, you +cannot have both custom tag `{func}` and block tag `{func}..{/func}`. + +- By default, your function implementation is called twice by Smarty: + once for the opening tag, and once for the closing tag. (See + `$repeat` below on how to change this.) + +- Only the opening tag of the block has attributes. All attributes are contained in the `$params` + variable as an associative array. The opening tag attributes are + also accessible to your function when processing the closing tag. + +- The value of the `$content` variable depends on whether your + function is called for the opening or closing tag. In case of the + opening tag, it will be NULL, and in case of the closing tag it will + be the contents of the template block. Note that the template block + will have already been processed by Smarty, so all you will receive + is the template output, not the template source. + +- The parameter `$repeat` is passed by reference to the function + implementation and provides a possibility for it to control how many + times the block is displayed. By default `$repeat` is TRUE at the + first call of the block function (the opening tag) and FALSE on all + subsequent calls to the block function (the block's closing tag). + Each time the function implementation returns with `$repeat` being + TRUE, the contents between `{func}...{/func}` are evaluated and the + function implementation is called again with the new block contents + in the parameter `$content`. + +Example: +```php +<?php + +function smarty_block_translate($params, $content, \Smarty\Template $template, &$repeat) { + // only output on the closing tag + if (!$repeat){ + if (isset($content)) { + $lang = $params['lang']; + // do some intelligent translation thing here with $content + return $translation; + } + } +} + +$smarty->registerPlugin(Smarty\Smarty::PLUGIN_BLOCK, 'translate', 'smarty_block_translate'); +``` + +This can now be used in your templates as follows: + +```smarty +{translate lang='nl'} + Quia omnis nulla omnis iusto est id et. +{/translate} +``` diff --git a/docs/api/extending/extensions.md b/docs/api/extending/extensions.md new file mode 100644 index 00000000..5c87d4dc --- /dev/null +++ b/docs/api/extending/extensions.md @@ -0,0 +1,101 @@ +# Creating an extension + +## Default extensions + +In order to organize your custom tags and modifiers, you can create an Extension. +In fact, most of Smarty itself is organized into two extensions: + +- the core extension, which provides the basic language tags such as `{if}`, `{for}` and `{assign}`. +- the default extension, which provides all default modifiers such as `|escape`, `|nl2br` and `|number_format` + and tags such as `{html_image}`, `{mailto}` and `{textformat}` that are enabled by default, but not necessarily universal. + +> ** Note ** +> +> There is also the 'BCPluginsAdapter' extension, which does not add any new functionality, but +> wraps calls to deprecated methods such as `Smarty\Smarty::addPluginsDir()` and `Smarty\Smarty::loadFilter()`. + +## Writing your own extension + +In order to write your own custom extension, you must write a class that implements `Smarty\Extension\ExtensionInterface`. +However, it is usually easier to extend `Smarty\Extension\Base` which provides empty implementation for each of the methods +required by `Smarty\Extension\ExtensionInterface`. This allows you to only override the method(s) you need. + +Example: +```php +<?php + +use Smarty\Extension\Base; + +class MyExtension extends Base { + + public function getModifierCompiler(string $modifier): ?\Smarty\Compile\Modifier\ModifierCompilerInterface { + + switch ($modifier) { + case 'array_escape': return new MyArrayEscapeModifierCompiler(); + case 'array_unescape': return new MyArrayUnescapeModifierCompiler(); + } + + return null; + } +} + +``` +Another example, that would allow you to use any valid PHP callable as a modifier in your templates: + +```php +<?php + +use Smarty\Extension\Base; + +class MyCallablePassThroughExtension extends Base { + + public function getModifierCallback(string $modifierName) { + + if (is_callable($modifierName)) { + return $modifierName; + } + + return null; + } +} + +``` + +Writing an extension allows you to add a group of tags, block tags and modifiers to the Smarty language. +It also allows you to register pre-, post- and output-filters in a structured way. +The files in `src/Extension/` in the `smarty/smarty` dir should give you all the information you need to start +writing your own extension. + +## Registering an extension + +When you have written your extension, add it to a Smarty instance as follows: + +```php +<?php + +use Smarty\Smarty; + +$smarty = new Smarty(); + +$smarty->addExtension(new MyCustomExtension()); +``` + +This will add `MyCustomExtension` to the end of the extension list, meaning that you cannot override tags or modifiers +from one of Smarty's default extensions. + +Should you wish to insert your extension at the top of the extension list, or create a very limited Smarty version that +only contains the core extension, you can use `Smarty\Smarty::setExtensions()` to override the list of extensions. + +```php +<?php + +use Smarty\Smarty; + +$smarty = new Smarty(); + +$smarty->setExtensions([ + new Smarty\Extension\CoreExtension(), + new MyCustomExtension(), + new Smarty\Extension\DefaultExtension(), +]); +```
\ No newline at end of file diff --git a/docs/api/extending/introduction.md b/docs/api/extending/introduction.md new file mode 100644 index 00000000..69cbce2a --- /dev/null +++ b/docs/api/extending/introduction.md @@ -0,0 +1,10 @@ +# Extending Smarty + +By default, Smarty is already very complete and powerful. However, you can unlock its real potential by +extending Smarty. + +There are various ways to extend Smarty for it to suit your needs. You can create custom +[tags](tags.md), [block tags](block-tags.md) and [modifiers](modifiers.md) by registering a method as a plugin. + +If this becomes too messy, you can group your custom tags, modifiers, and more into an [Extension](extensions.md). + diff --git a/docs/api/extending/modifiers.md b/docs/api/extending/modifiers.md new file mode 100644 index 00000000..78540cf9 --- /dev/null +++ b/docs/api/extending/modifiers.md @@ -0,0 +1,27 @@ +# Custom modifiers + +Modifiers are little functions that are applied +to a variable in the template before it is displayed or used in some +other context. Smarty comes with a bunch of [modifiers](../../designers/language-modifiers/index.md), but you can +easily add your own. + +In order to do so, you must write a function that accepts as its first parameter the value on which the +modifier is to operate. The rest of the parameters are optional, depending on what kind of operation is to be performed. + +The modifier has to return the result of its processing. + +For example: +```php +<?php + +function smarty_modifier_substr($string, $offset, $length) { + return substr($string, $offset, $length); +} + +$smarty->registerPlugin(Smarty\Smarty::PLUGIN_MODIFIER, 'substr', 'smarty_modifier_substr'); +``` + +You can now use this in your templates as follows: +```smarty +{$applicationName|substr:0:20} +``` diff --git a/docs/api/extending/tags.md b/docs/api/extending/tags.md new file mode 100644 index 00000000..38cd4e92 --- /dev/null +++ b/docs/api/extending/tags.md @@ -0,0 +1,84 @@ +# Custom tags + +You can add your own tags to the Smarty language. + +## Runtime tags + +Usually, you'll add a runtime tag. Adding a runtime tag requires you to provide a callback function that accepts +two parameters: + +- `$params`: all attributes from the template as an associative array. +- `$template`: a `Smarty\Template` object representing the template where tag was used. + +The output (return value) of the function will be substituted in place +of the tag in the template. + +If the function needs to assign some variables to the template or use +some other Smarty-provided functionality, it can use the supplied +`$template` object to do so. + +```php +<?php + +function smarty_tag_eightball($params, \Smarty\Template $template): string { + $answers = [ + 'Yes', + 'No', + 'No way', + 'Outlook not so good', + 'Ask again soon', + 'Maybe in your reality' + ]; + + $result = array_rand($answers); + return $answers[$result]; +} + +$smarty->registerPlugin(Smarty\Smarty::PLUGIN_FUNCTION, 'eightball', 'smarty_tag_eightball'); +``` + +Which can now be used in the template as: + +```smarty +Question: Will we ever have time travel? +Answer: {eightball}. +``` + +## Compiler tags + +Compiler tags 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 runtime tag registered under the same name, +the compiler function has precedence. + +The compiler function is passed two parameters: the params array which +contains precompiled strings for the attribute values and the Smarty +object. It's supposed to return the code to be injected into the +compiled template including the surrounding PHP tags. + +Example: +```php +<?php + +function smarty_compiler_tplheader($params, Smarty $smarty) { + return "<?php\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>"; +} + +$smarty->registerPlugin(Smarty\Smarty::PLUGIN_COMPILER, 'tplheader', 'smarty_compiler_tplheader'); +``` + +This function can be called from the template as: + +```smarty +{* this function gets executed at compile time only *} +{tplheader} +``` + +The resulting PHP code in the compiled template would be something like +this: + +```php +<?php +echo 'index.tpl compiled at 2023-02-20 20:02'; +``` diff --git a/docs/api/filters/output-filters.md b/docs/api/filters/output-filters.md new file mode 100644 index 00000000..9de31892 --- /dev/null +++ b/docs/api/filters/output-filters.md @@ -0,0 +1,35 @@ +# Output filters + +When a template is rendered, its output can be sent through one or more +output filters. + +> **Note** +> This differs from [`prefilters`](prefilters.md) and +> [`postfilters`](postfilters.md) because, pre- and postfilters +> operate on compiled templates before they are saved to the disk, whereas +> output filters operate on the template output when it is executed. + +Smarty will pass the template output as the first argument, and expect the function +to return the result of the processing. + +Output filters can be either added as part of an [Extension](../extending/extensions.md) or +registered as shown below. + +This will provide a rudimentary protection against spambots: +```php +<?php + +function protect_email($tpl_output, \Smarty\Template\ $template) +{ + return preg_replace( + '!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!', + '$1%40$2', + $tpl_output + ); +} + +// register the outputfilter +$smarty->registerFilter("output", "protect_email"); +$smarty->display("index.tpl'); + +``` diff --git a/docs/api/filters/postfilters.md b/docs/api/filters/postfilters.md new file mode 100644 index 00000000..0f4ba9dc --- /dev/null +++ b/docs/api/filters/postfilters.md @@ -0,0 +1,33 @@ +# Postfilters + +Template postfilters are PHP functions that your templates are ran +through *after they are compiled*. + +Smarty will +pass the compiled template code as the first argument, and expect the +function to return the result of the processing, which must also be valid PHP code. + +Prefilters can be either added as part of an [Extension](../extending/extensions.md) or +registered as shown below. + + +```php +<?php + +function add_header_comment($tpl_source, \Smarty\Template\ $template) +{ + return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source; +} + +// register the postfilter +$smarty->registerFilter('post', 'add_header_comment'); +$smarty->display('index.tpl'); +``` + +The postfilter above will make the compiled Smarty template `index.tpl` +look like: + +```smarty +<!-- Created by Smarty! --> +{* rest of template content... *} +``` diff --git a/docs/api/filters/prefilters.md b/docs/api/filters/prefilters.md new file mode 100644 index 00000000..2d5c19f9 --- /dev/null +++ b/docs/api/filters/prefilters.md @@ -0,0 +1,26 @@ +# 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. + +Smarty will pass the template source code as the first argument, and +expect the function to return the resulting template source code. + +Prefilters can be either added as part of an [Extension](../extending/extensions.md) or +registered as shown below. + +This will remove all the html comments in the template source: +```php +<?php + +function remove_dw_comments($tpl_source, \Smarty\Template\ $template) +{ + return preg_replace("/<!--#.*-->/U",'',$tpl_source); +} + +// register the prefilter +$smarty->registerFilter('pre', 'remove_dw_comments'); +$smarty->display('index.tpl'); +``` diff --git a/docs/api/inheritance.md b/docs/api/inheritance.md new file mode 100644 index 00000000..f58369e6 --- /dev/null +++ b/docs/api/inheritance.md @@ -0,0 +1,130 @@ +# Template Inheritance + +Inheritance allows you to define base templates that can +be extended by child templates. Extending means that the child template +can override all or some of the named block areas in the base template. + +When you render the child template, the result will as if you rendered +the base template, with only the block(s) that you have overridden in the +child templates differing. + +- The inheritance tree can be as deep as you want, meaning you can + extend a file that extends another one that extends another one and + so on. + +- The child templates can not define any content besides what's + inside [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags they override. + Anything outside of [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags will + be removed. + +- Template inheritance is a compile time process which creates a + single compiled template file. Compared to corresponding solutions + based on subtemplates included with the + [`{include}`](../designers/language-builtin-functions/language-function-include.md) tag it does have much + better performance when rendering. + +## Basic inheritance + +First, create a base template with one or more [blocks](../designers/language-builtin-functions/language-function-block.md). +Then, create a child template. The child template +must have an [{extends} tag](../designers/language-builtin-functions/language-function-extends.md) on its first line. + +The child template can redefine one or more blocks defined in the base template. + +See below for a simple example. + +layout.tpl (base) + +```smarty +<html> + <head> + <title>{block name=title}Default Page Title{/block}</title> + {block name=head}{/block} + </head> + <body> + {block name=body}{/block} + </body> +</html> +``` + + +myproject.tpl (child) + +```smarty +{extends file='layout.tpl'} +{block name=head} + <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> + <script src="/js/mypage.js"></script> +{/block} +``` + +mypage.tpl (grandchild) + +```smarty +{extends file='myproject.tpl'} +{block name=title}My Page Title{/block} +{block name=head} + <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> + <script src="/js/mypage.js"></script> +{/block} +{block name=body}My HTML Page Body goes here{/block} +``` + + +To render the above, you would use: + +```php +<?php +$smarty->display('mypage.tpl'); +``` + +The resulting output is: + +```html +<html> + <head> + <title>My Page Title</title> + <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> + <script src="/js/mypage.js"></script> + </head> + <body> + My HTML Page Body goes here + </body> +</html> +``` + +> **Note** +> +> When [compile-check](./configuring.md#disabling-compile-check) is enabled, all files +> in the inheritance tree +> are checked for modifications upon each invocation. You may want to +> disable compile-check on production servers for this reason. + +> **Note** +> +> If you have a subtemplate which is included with +> [`{include}`](../designers/language-builtin-functions/language-function-include.md) and it contains +> [`{block}`](../designers/language-builtin-functions/language-function-block.md) areas it works only if the +> [`{include}`](../designers/language-builtin-functions/language-function-include.md) itself is called from within +> a surrounding [`{block}`](../designers/language-builtin-functions/language-function-block.md). In the final +> parent template you may need a dummy +> [`{block}`](../designers/language-builtin-functions/language-function-block.md) for it. + + +## Using append and prepend +The content of [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags from child +and parent templates can be merged by the `append` or `prepend` +[`{block}`](../designers/language-builtin-functions/language-function-block.md) tag option flags and +`{$smarty.block.parent}` or `{$smarty.block.child}` placeholders. + +## Extends resource type +Instead of using [`{extends}`](../designers/language-builtin-functions/language-function-extends.md) tags in the +template files you can define the inheritance tree in your PHP script by +using the [`extends:` resource](resources.md#the-extends-resource) type. + +The code below will return same result as the example above. + +```php +<?php +$smarty->display('extends:layout.tpl|myproject.tpl|mypage.tpl'); +``` diff --git a/docs/api/rendering.md b/docs/api/rendering.md new file mode 100644 index 00000000..a66b6126 --- /dev/null +++ b/docs/api/rendering.md @@ -0,0 +1,86 @@ +# Rendering templates + +## Fetching or rendering templates directly +As explained in [basics](basics.md), you can use `$smarty->fetch()` or `$smarty->display()` +to render a template directly. + +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->display('homepage.tpl'); + +// or + +$output = $smarty->fetch('homepage.tpl'); +``` + +When you use `display()`, Smarty renders the template to the standard output stream. +`fetch()` returns the output instead of echoing it. + +The example above uses simple filenames to load the template. Smarty also supports +[loading templates from resources](resources.md). + +## Creating a template object +You can also create a template object which later can be prepared first, +and rendered later. This can be useful, for example if you plan to re-use several +templates. + +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +// create template object with its private variable scope +$tpl = $smarty->createTemplate('index.tpl'); + +// assign a variable (available only to this template) +$tpl->assign('title', 'My Homepage!'); + +// display the template +$tpl->display(); +``` + +More on assigning variables in [using data in templates](variables/assigning.md). + + +## Testing if a template exists +You can use `templateExists()` to check whether a template exists before you attempt to use it. + +It accepts either a path to the template on the filesystem or a +resource string specifying the template. + +This example uses `$_GET['page']` to +[`{include}`](../designers/language-builtin-functions/language-function-include.md) a content template. If the +template does not exist then an error page is displayed instead. First, +the `page_container.tpl` + +```smarty +<html> + <head> + <title>{$title|escape}</title> + </head> + <body> + {* include middle content page *} + {include file=$content_template} + </body> +</html> +``` + +And the php script: + +```php +<?php + +// set the filename eg index.inc.tpl +$mid_template = $_GET['page'].'.inc.tpl'; + +if (!$smarty->templateExists($mid_template)){ + $mid_template = 'page_not_found.tpl'; +} +$smarty->assign('content_template', $mid_template); + +$smarty->display('page_container.tpl'); +``` diff --git a/docs/api/resources.md b/docs/api/resources.md new file mode 100644 index 00000000..5ca52b12 --- /dev/null +++ b/docs/api/resources.md @@ -0,0 +1,322 @@ +# Template resources + +## The filesystem resource + +So far in our examples, we have used simple filenames or paths when loading a template. + +For example, to load a template file called `homepage.tpl`, from the filesystem, you could write: +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->display('homepage.tpl'); +``` + +The filesystem is the default resource. Templates, however, may come +from a variety of sources. When you render a template, or +when you include a template from within another template, you supply a +resource type, followed by `:` and the appropriate path and template name. + +If a resource is not explicitly given, the default resource type is assumed. +The resource type for the filesystem is `file`, which means that the previous example +can be rewritten as follows: +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->display('file:homepage.tpl'); +``` + +The file resource pulls templates source files from the directories +specified using `Smarty::setTemplateDir()` (see [Configuring Smarty](configuring.md)). + +`setTemplateDir` accepts a single path, but can also ben called with an array of paths. +In that case, the list of directories is traversed in the order they appear in the array. The +first template found is the one to process. + +### Templates from a specific directory + +Smarty 3.1 introduced the bracket-syntax for specifying an element from +`Smarty::setTemplateDir()`. This allows websites +employing multiple sets of templates better control over which template +to access. + +The bracket-syntax can be used as follows: +```php +<?php + +// setup template directories +$smarty->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 +``` + +And, from within a Smarty template: + +```smarty +{include file="file:foo.tpl"} +{* will load ./templates/foo.tpl *} + +{include file="file:[1]foo.tpl"} +{* will load ./templates_2/foo.tpl *} + +{include file="file:[foo]foo.tpl"} +{* will load ./templates_foo/foo.tpl *} +``` + +### Using absolute paths + +Templates outside the specified template directories +require the `file:` template resource type, followed by the absolute +path to the template (with leading slash). + +```php +<?php +$smarty->display('file:/export/templates/index.tpl'); +$smarty->display('file:/path/to/my/templates/menu.tpl'); +```` + +And from within a Smarty template: +```smarty +{include file='file:/usr/local/share/templates/navigation.tpl'} +``` + +> **Note** +> +> With [`Security`](security.md) enabled, access to +> templates outside of the specified templates directories is +> not allowed unless you whitelist those directories. + +### Windows file paths +If you are running on Windows, file paths usually include a drive +letter (such as `C:`) at the beginning of the pathname. Be sure to use `file:` in +the path to avoid namespace conflicts and get the desired results. +```php +<?php +$smarty->display('file:C:/export/templates/index.tpl'); +$smarty->display('file:F:/path/to/my/templates/menu.tpl'); +``` + +And from within Smarty template: +```smarty +{include file='file:D:/usr/local/share/templates/navigation.tpl'} +``` + +### Handling missing templates +If the file resource cannot find the requested template, it will check if there is +a default template handler to call. By default, there is none, and Smarty will return an error, +but you can register a default template handler calling `Smarty::registerDefaultTemplateHandler` +with any [callable](https://www.php.net/manual/en/language.types.callable.php). + +```php +<?php + +$smarty->registerDefaultTemplateHandler([$this, 'handleMissingTemplate']); + +// ... + +public function handleMissingTemplate($type, $name, &$content, &$modified, Smarty $smarty) { + if (/* ... */) { + // return corrected filepath + return "/tmp/some/foobar.tpl"; + } elseif (/* ... */) { + // return a template directly + $content = "the template source"; + $modified = time(); + return true; + } else { + // tell smarty that we failed + return false; + } +} + +``` + +## The string and eval resources + +Smarty can render templates from a string by using the `string:` or +`eval:` resource. + +- The `string:` resource behaves much the same as a template file. The + template source is compiled from a string and stores the compiled + template code for later reuse. Each unique template string will + create a new compiled template file. If your template strings are + accessed frequently, this is a good choice. If you have frequently + changing template strings (or strings with low reuse value), the + `eval:` resource may be a better choice, as it doesn\'t save + compiled templates to disk. + +- The `eval:` resource evaluates the template source every time a page + is rendered. This is a good choice for strings with low reuse value. + If the same string is accessed frequently, the `string:` resource + may be a better choice. + +> **Note** +> +> With a `string:` resource type, each unique string generates a +> compiled file. Smarty cannot detect a string that has changed, and +> therefore will generate a new compiled file for each unique string. It +> is important to choose the correct resource so that you do not fill +> your disk space with wasted compiled strings. + +```php +<?php +$smarty->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 +``` +From within a Smarty template: +```smarty +{include file="string:$template_string"} {* compiles for later reuse *} +{include file="eval:$template_string"} {* compiles every time *} +``` + +Both `string:` and `eval:` resources may be encoded with +[`urlencode()`](https://www.php.net/urlencode) or +[`base64_encode()`](https://www.php.net/urlencode). This is not necessary +for the usual use of `string:` and `eval:`, but is required when using +either of them in conjunction with the [`extends resource`](#the-extends-resource). + +```php + <?php + $smarty->assign('foo','value'); + $template_string_urlencode = urlencode('display {$foo} here'); + $template_string_base64 = base64_encode('display {$foo} here'); + $smarty->display('eval:urlencode:' . $template_string_urlencode); // will decode string using urldecode() + $smarty->display('eval:base64:' . $template_string_base64); // will decode string using base64_decode() +``` + +From within a Smarty template: +```smarty + {include file="string:urlencode:$template_string_urlencode"} {* will decode string using urldecode() *} + {include file="eval:base64:$template_string_base64"} {* will decode string using base64_decode() *} +``` + +## The extends resource + +The `extends:` resource is used to define child/parent relationships. For details see section of +[Template inheritance](inheritance.md). + +> **Note** +> +> Using the extends resource is usually not necessary. If you have a choice, it is normally more flexible and +> intuitive to handle inheritance chains from within the templates using the [{extends} tag](inheritance.md). + +When `string:` and `eval:` templates are used, make sure they are properly url or base64 encoded. + +The templates within an inheritance chain are not compiled separately. Only a single compiled template will be generated. +(If an `eval:` resource is found within an inheritance chain, its "don't save a compile file" property is superseded by +the `extends:` resource.) + +Example: +```php +<?php +$smarty->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}'); +``` + +## The stream resource + +Smarty allow you to use [PHP streams](https://www.php.net/manual/en/function.stream-wrapper-register.php) +as a template resource. Smarty will first look for a registered template resource. If nothing is +found, it will check if a PHP stream is available. If a stream is available, Smarty will use it +to fetch the template. + +For example, +```php +<?php +stream_wrapper_register('myresource', MyResourceStream::class); +$smarty->display('myresource:bar.tpl'); +``` + +Or, from within a template: +```smarty + {include file="myresource:bar.tpl"} +``` + +## Adding your own resource type +You can create a class that extends `Smarty\Resource\CustomPlugin` to add your own resource type, +for example to load template from a database. + +For example: +```php +<?php +class HelloWorldResource extends Smarty\Resource\CustomPlugin { + + protected function fetch($name, &$source, &$mtime) { + $source = '{$x="hello world"}{$x}'; // load your template here based on $name + $mtime = time(); + } + +} + +// .. + +$smarty->registerResource('helloworld', new HelloWorldResource()); +``` + +If a Resource's templates should not be run through the Smarty +compiler, the Custom Resource may extend `\Smarty\Resource\UncompiledPlugin`. +The Resource Handler must then implement the function +`renderUncompiled(\Smarty\Template $_template)`. `$_template` is +a reference to the current template and contains all assigned variables +which the implementor can access via +`$_template->getSmarty()->getTemplateVars()`. These Resources simply echo +their rendered content to the output stream. The rendered output will be +output-cached if the Smarty instance was configured accordingly. See +`src/Resource/PhpPlugin.php` for an example. + +If the Resource's compiled templates should not be cached on disk, the +Custom Resource may extend `\Smarty\Resource\RecompiledPlugin`. These Resources +are compiled every time they are accessed. This may be an expensive +overhead. See `src/Resource/StringEval.php` for an +example. + +## Changing the default resource type +The default resource type is `file`. If you want to change it, use `Smarty::setDefaultResourceType`. + +The following example will change the default resource type to `mysql`: +```php +<?php +$smarty->setDefaultResourceType('mysql'); +``` diff --git a/docs/api/security.md b/docs/api/security.md new file mode 100644 index 00000000..07120afd --- /dev/null +++ b/docs/api/security.md @@ -0,0 +1,119 @@ +# Security + +Security is good for situations when you have untrusted parties editing +the templates, and you want to reduce the risk of system +security compromises through the template language. + +The settings of the security policy are defined by overriding public properties of an +instance of the \Smarty\Security class. These are the possible settings: + +- `$secure_dir` is an array of template directories that are + considered secure. A directory configured using `$smarty->setTemplateDir()` is + considered secure implicitly. The default is an empty array. +- `$trusted_uri` is an array of regular expressions matching URIs that + are considered trusted. This security directive is used by + [`{fetch}`](../designers/language-custom-functions/language-function-fetch.md) and + [`{html_image}`](../designers/language-custom-functions/language-function-html-image.md). URIs passed to + these functions are reduced to `{$PROTOCOL}://{$HOSTNAME}` to allow + simple regular expressions (without having to deal with edge cases + like authentication-tokens). + + The expression `'#https?://.*smarty.net$#i'` would allow accessing + the following URIs: + + - `http://smarty.net/foo` + - `http://smarty.net/foo` + - `http://www.smarty.net/foo` + - `http://smarty.net/foo` + - `https://foo.bar.www.smarty.net/foo/bla?blubb=1` + + but deny access to these URIs: + + - `http://smarty.com/foo` (not matching top-level domain \"com\") + - `ftp://www.smarty.net/foo` (not matching protocol \"ftp\") + - `http://www.smarty.net.otherdomain.com/foo` (not matching end of + domain \"smarty.net\") + +- `$static_classes` is an array of classes that are considered + trusted. The default is an empty array which allows access to all + static classes. To disable access to all static classes set + $static_classes = null. + +- `$streams` is an array of streams that are considered trusted and + can be used from within template. To disable access to all streams + set $streams = null. An empty array ( $streams = [] ) will + allow all streams. The default is array('file'). + +- `$allowed_modifiers` is an array of (registered / autoloaded) + modifiers that should be accessible to the template. If this array + is non-empty, only the herein listed modifiers may be used. This is + a whitelist. + +- `$disabled_modifiers` is an array of (registered / autoloaded) + modifiers that may not be accessible to the template. + +- `$allowed_tags` is a boolean flag which controls if constants can + function-, block and filter plugins that should be accessible to the + template. If this array is non-empty, only the herein listed + modifiers may be used. This is a whitelist. + +- `$disabled_tags` is an array of (registered / autoloaded) function-, + block and filter plugins that may not be accessible to the template. + +- `$allow_constants` is a boolean flag which controls if constants can + be accessed by the template. The default is "true". + +- `$allow_super_globals` is a boolean flag which controls if the PHP + super globals can be accessed by the template. The default is + "true". + +If security is enabled, no private methods, functions or properties of +static classes or assigned objects can be accessed (beginning with +'_') by the template. + +To customize the security policy settings you can extend the +\Smarty\Security class or create an instance of it. + +```php +<?php + +use Smarty\Smarty; + +class My_Security_Policy extends \Smarty\Security { + public $allow_constants = false; +} + +$smarty = new Smarty(); + +$smarty->enableSecurity('My_Security_Policy'); +``` + +```php +<?php + +use Smarty\Smarty; + +$smarty = new Smarty(); + +$my_security_policy = new \Smarty\Security($smarty); +$my_security_policy->allow_constants = false; + +$smarty->enableSecurity($my_security_policy); +``` + +```php +<?php + +use Smarty\Smarty; + +$smarty = new Smarty(); + +// enable default security +$smarty->enableSecurity(); +``` + +> **Note** +> +> Most security policy settings are only checked when the template gets +> compiled. For that reason you should delete all cached and compiled +> template files when you change your security settings. diff --git a/docs/api/variables/assigning.md b/docs/api/variables/assigning.md new file mode 100644 index 00000000..3aa606b6 --- /dev/null +++ b/docs/api/variables/assigning.md @@ -0,0 +1,139 @@ +# Assigning variables + +Templates start to become really useful once you know how to use variables. + +## Basic assigning +Let's revisit the example from the [basics section](../basics.md). The following script assigns a value to +the 'companyName' variable and renders the template: + +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$smarty->assign('companyName', 'AC & ME Corp.'); + +$smarty->display('footer.tpl'); +``` + +footer.tpl: +```smarty +<small>Copyright {$companyName|escape}</small> +``` + +Smarty will apply the [escape modifier](../designers/language-modifiers/language-modifier-escape.md) +to the value assigned to the variable +`companyName` and replace `{$companyName|escape}` with the result. + +```html +<small>Copyright AC & ME Corp.</small> +``` + +Using `$smarty->assign()` is the most common way of assigning data to templates, but there are several other methods. + +## Appending data to an existing variable +Using `append()`, you can add data to an existing variable, usually an array. + +If you append to a string value, it is converted to an array value and +then appended to. You can explicitly pass name/value pairs, or +associative arrays containing the name/value pairs. If you pass the +optional third parameter of TRUE, the value will be merged with the +current array instead of appended. + +Examples: + +```php +<?php +// This is effectively the same as assign() +$smarty->append('foo', 'Fred'); +// After this line, foo will now be seen as an array in the template +$smarty->append('foo', 'Albert'); + +$array = [1 => 'one', 2 => 'two']; +$smarty->append('X', $array); +$array2 = [3 => 'three', 4 => 'four']; +// The following line will add a second element to the X array +$smarty->append('X', $array2); + +// passing an associative array +$smarty->append(['city' => 'Lincoln', 'state' => 'Nebraska']); +``` + +## Assigning to template objects +When you use a template objects, as explained in [rendering a template](../rendering.md#creating-a-template-object), +you can assign data to the template objects directly instead of assigning it to Smarty. This way, you can use different +sets of data for different templates. + +For example: +```php +<?php + +use Smarty\Smarty; +$smarty = new Smarty(); + +$tplBlue = $smarty->createTemplate('blue.tpl'); +$tplBlue->assign('name', 'The one'); +$tplBlue->display(); + +$tplRed = $smarty->createTemplate('red.tpl'); +$tplRed->assign('name', 'Neo'); +$tplRed->display(); +``` + +## Using data objects +For more complex use cases, Smarty supports the concept of data objects. +Data objects are containers to hold data. Data objects can be attached to templates when creating them. +This allows for fine-grained re-use of data. + +For example: +```php +<?php +use Smarty\Smarty; +$smarty = new Smarty; + +// create a data object +$data = $smarty->createData(); + +// assign variable to the data object +$data->assign('name', 'Neo'); + +// create template object which will use variables from the data object +$tpl = $smarty->createTemplate('index.tpl', $data); + +// display the template +$tpl->display(); +``` + +## Clearing assigned data +When re-using templates, you may need to clear data assigned in a previous run. Use `clearAllAssign()` to +clear the values of all assigned variables on data objects, template objects or the Smarty object. + +Examples: +```php +<?php +// assigning data to the Smarty object +$smarty->assign('Name', 'Fred'); +// ... +$smarty->clearAllAssign(); + +// using a data object +$data = $smarty->createData(); +$data->assign('name', 'Neo'); +// ... +$data->clearAllAssign(); + +// using a template +$tplBlue = $smarty->createTemplate('blue.tpl'); +$tplBlue->assign('name', 'The one'); +// ... +$tplBlue->clearAllAssign(); +``` + +Note that there it's only useful to clear assigned data if you: + +1. repeatedly re-use templates, and +2. the variables used may change on each repetition + +If your script simply runs once and then ends, or you always assign the same variables, clearing assigned data +is of no use.
\ No newline at end of file diff --git a/docs/api/variables/config-files.md b/docs/api/variables/config-files.md new file mode 100644 index 00000000..181733ea --- /dev/null +++ b/docs/api/variables/config-files.md @@ -0,0 +1,89 @@ +# Loading data from config files + +Instead of [assigning data to templates from PHP](assigning.md), you can also +use a config file. + +## Example config file +Config files are best suited to manage template settings +from one file. One example is a multi-language application. +Instead of writing multiple templates to support different languages, +you can write a single template file and load your language dependent strings +from config files. + +Example `lang.en.ini`: +```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.""" + +``` + +Values of [config file variables](./language-variables/language-config-variables.md) can be in +quotes, but not necessary. You can use either single or double quotes. +If you have a value that spans more than one line, enclose the entire +value with triple quotes \("""\). You can put comments into config +files by any syntax that is not a valid config file syntax. We recommend +using a `#` (hash) at the beginning of the line. + +The example config file above has two sections. Section names are +enclosed in \[brackets\]. Section names can be arbitrary strings not +containing `[` or `]` symbols. The variable at the top is a global +variable. Global variables are always +loaded from the config file. If a particular section is loaded, then the +global variables and the variables from that section are also loaded. If +a variable exists both as a global and in a section, the section +variable is used. + +## Loading a config file + +Config files are loaded into templates with the built-in template +function [`{config_load}`](../../designers/language-builtin-functions/language-function-config-load.md) or by calling +`configLoad()` from PHP: + +```php +<?php +$smarty->configLoad('lang.en.ini'); +``` + +Load a specific section with: + +```php +<?php +$smarty->configLoad('lang.en.ini', 'Customer'); +``` + +Note that the global section will always be loaded. + +## Retrieving config variables in PHP + + +## Loading from a resource +Config files (or resources) are loaded by the same resource facilities +as templates. That means that a config file can also be loaded from a db. See [resources](../resources.md) +for more information. + +## Config overwrite +If you name two variables the same within a section, +the last one will be used unless you call: +```php +<?php +$smarty->setConfigOverwrite(false); +``` +When config overwrite is disabled, Smarty will create arrays of config file variables when it encounters +multiple entries with the same name. + +See also [`{config_load}`](./language-builtin-functions/language-function-config-load.md), +[`$config_overwrite`](../programmers/api-variables/variable-config-overwrite.md), +[`$default_config_handler_func`](../programmers/api-variables/variable-default-config-handler-func.md), +[`getConfigVars()`](../programmers/api-functions/api-get-config-vars.md), +[`clearConfig()`](../programmers/api-functions/api-clear-config.md) and +[`configLoad()`](../programmers/api-functions/api-config-load.md) diff --git a/docs/api/variables/objects.md b/docs/api/variables/objects.md new file mode 100644 index 00000000..1d0d7e33 --- /dev/null +++ b/docs/api/variables/objects.md @@ -0,0 +1,106 @@ +# Objects + +Smarty allows access to PHP [objects](https://www.php.net/object) through +the templates. + +> **Note** +> +> When you assign/register objects to templates, be sure that all +> properties and methods accessed from the template are for presentation +> purposes only. It is very easy to inject application logic through +> objects, and this leads to poor designs that are difficult to manage. +> See the Best Practices section of the Smarty website. + +There are two ways to access them. + +## Assign the object +You can assign objects to a template and access them much like any other assigned variable. + +Example: +```php +<?php +// the object + +class My_Object { + public function meth1($params, $smarty_obj) { + return 'this is my meth1'; + } +} + +// We can also assign objects. assign_by_ref when possible. +$smarty->assign('myobj', new My_Object()); + +$smarty->display('index.tpl'); +``` + +And here's how to access your object in `index.tpl`: + +```smarty +{$myobj->meth1('foo',$bar)} +``` + + + +## Register the object +Registerd objects use a different template syntax. Also, a registered object +can be restricted to certain methods or +properties. However, **a registered object cannot be looped over or +assigned in arrays of objects**, etc. + +If security is enabled, no private methods or functions can be accessed +(beginning with '_'). If a method and property of the same name exist, +the method will be used. + +You can restrict the methods and properties that can be accessed by +listing them in an array as the third registration parameter. + +By default, parameters passed to objects through the templates are +passed the same way [custom functions](../../designers/language-custom-functions/index.md) get +them. An associative array is passed as the first parameter, and the +smarty object as the second. If you want the parameters passed one at a +time for each argument like traditional object parameter passing, set +the fourth registration parameter to FALSE. + +The optional fifth parameter has only effect with `format` being TRUE +and contains a list of methods that should be treated as blocks. That +means these methods have a closing tag in the template +(`{foobar->meth2}...{/foobar->meth2}`) and the parameters to the methods +have the same synopsis as the parameters for +[`block tags`](../extending/block-tags.md): They get the four +parameters `$params`, `$content`, `$smarty` and `&$repeat` and they also +behave like block tags. + +```php +<?php +// the object + +class My_Object { + function meth1($params, $smarty_obj) { + return 'this is my meth1'; + } +} + +$myobj = new My_Object; + +// registering the object +$smarty->registerObject('foobar', $myobj); + +// if we want to restrict access to certain methods or properties, list them +$smarty->registerObject('foobar', $myobj, array('meth1','meth2','prop1')); + +// if you want to use the traditional object parameter format, pass a boolean of false +$smarty->registerObject('foobar', $myobj, null, false); + +$smarty->display('index.tpl'); +``` + +And here's how to access your objects in `index.tpl`: + +```smarty +{* access our registered object *} +{foobar->meth1 p1='foo' p2=$bar} + +{* you can also assign the output *} +{foobar->meth1 p1='foo' p2=$bar assign='output'} +the output was {$output} +``` diff --git a/docs/api/variables/static-class-methods.md b/docs/api/variables/static-class-methods.md new file mode 100644 index 00000000..fd3fea4c --- /dev/null +++ b/docs/api/variables/static-class-methods.md @@ -0,0 +1,39 @@ +# Static Classes + +You can directly access static classes. The syntax is roughly the same as in +PHP. + +> **Note** +> +> Direct access to PHP classes is not recommended. This ties the +> underlying application code structure directly to the presentation, +> and also complicates template syntax. It is recommended to register +> plugins which insulate templates from PHP classes/objects. Use at your +> own discretion. + +## Examples + +**class constant BAR** +```smarty +{assign var=foo value=myclass::BAR} +``` + +**method result** +```smarty +{assign var=foo value=myclass::method()} +``` + +**method chaining** +```smarty +{assign var=foo value=myclass::method1()->method2} +``` + +**property bar of class myclass** +```smarty +{assign var=foo value=myclass::$bar} +``` + +**using Smarty variable bar as class name** +```smarty +{assign var=foo value=$bar::method} +``` diff --git a/docs/api/variables/streams.md b/docs/api/variables/streams.md new file mode 100644 index 00000000..93d5c15e --- /dev/null +++ b/docs/api/variables/streams.md @@ -0,0 +1,13 @@ +# Streams + +You can also use streams to call variables. *{$foo:bar}* will use the +*foo://bar* stream to get the template variable. + +Using a PHP stream for a template variable resource from within a +template. + +```smarty +{$foo:bar} +``` + +See also [`Template Resources`](../resources.md) diff --git a/docs/appendixes/tips.md b/docs/appendixes/tips.md index 3c6e6b96..e4e38d4b 100644 --- a/docs/appendixes/tips.md +++ b/docs/appendixes/tips.md @@ -209,8 +209,7 @@ fetching the data up front? You can do this by writing a custom plugin for fetching the content and assigning it to a template variable. -`function.load_ticker.php` - drop file in -[`$plugins directory`](../programmers/api-variables/variable-plugins-dir.md) +`function.load_ticker.php` ```php diff --git a/docs/designers/chapter-debugging-console.md b/docs/designers/chapter-debugging-console.md index 6704fce2..50acd195 100644 --- a/docs/designers/chapter-debugging-console.md +++ b/docs/designers/chapter-debugging-console.md @@ -10,8 +10,7 @@ of the console. Set [`$debugging`](../programmers/api-variables/variable-debugging.md) to TRUE in Smarty, and if needed set [`$debug_tpl`](../programmers/api-variables/variable-debug-template.md) to the template resource -path to `debug.tpl` (this is in [`SMARTY_DIR`](../programmers/smarty-constants.md) by -default). When you load the page, a Javascript console window will pop +path to `debug.tpl`. When you load the page, a Javascript console window will pop up and give you the names of all the included templates and assigned variables for the current page. diff --git a/docs/designers/language-basic-syntax/index.md b/docs/designers/language-basic-syntax/index.md index c0a12a9b..05c0ba69 100644 --- a/docs/designers/language-basic-syntax/index.md +++ b/docs/designers/language-basic-syntax/index.md @@ -26,8 +26,8 @@ The basis components of the Smarty syntax are: - [Comments](language-syntax-comments.md) - [Variables](language-syntax-variables.md) +- [Operators](language-syntax-operators.md) - [Functions](language-syntax-functions.md) - [Attributes](language-syntax-attributes.md) - [Quotes](language-syntax-quotes.md) -- [Math](language-math.md) - [Escaping](language-escaping.md) diff --git a/docs/designers/language-basic-syntax/language-escaping.md b/docs/designers/language-basic-syntax/language-escaping.md index 4c75e09e..58e75d58 100644 --- a/docs/designers/language-basic-syntax/language-escaping.md +++ b/docs/designers/language-basic-syntax/language-escaping.md @@ -69,7 +69,7 @@ Where the template is: ```smarty Welcome <!--{$name}--> to Smarty -<script language="javascript"> + <script> var foo = <!--{$foo}-->; function dosomething() { alert("foo is " + foo); diff --git a/docs/designers/language-basic-syntax/language-math.md b/docs/designers/language-basic-syntax/language-math.md deleted file mode 100644 index a9a43efd..00000000 --- a/docs/designers/language-basic-syntax/language-math.md +++ /dev/null @@ -1,28 +0,0 @@ -# Math - -Math can be applied directly to variable values. - -## Examples -```smarty -{$foo+1} - -{$foo*$bar} - -{* some more complicated examples *} - -{$foo->bar-$bar[1]*$baz->foo->bar()-3*7} - -{if ($foo+$bar.test%$baz*134232+10+$b+10)} - -{$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"} - -{assign var="foo" value="`$foo+$bar`"} -``` - -> **Note** -> -> Although Smarty can handle some very complex expressions and syntax, -> it is a good rule of thumb to keep the template syntax minimal and -> focused on presentation. If you find your template syntax getting too -> complex, it may be a good idea to move the bits that do not deal -> explicitly with presentation to PHP by way of plugins or modifiers. diff --git a/docs/designers/language-basic-syntax/language-syntax-functions.md b/docs/designers/language-basic-syntax/language-syntax-functions.md index c3c8c21c..93d94f6b 100644 --- a/docs/designers/language-basic-syntax/language-syntax-functions.md +++ b/docs/designers/language-basic-syntax/language-syntax-functions.md @@ -11,7 +11,6 @@ within delimiters like so: `{funcname attr1="val1" attr2="val2"}`. {config_load file="colors.conf"} {include file="header.tpl"} -{insert file="banner_ads.tpl" title="My Site"} {if $logged_in} Welcome, <span style="color:{#fontColor#}">{$name}!</span> diff --git a/docs/designers/language-basic-syntax/language-syntax-operators.md b/docs/designers/language-basic-syntax/language-syntax-operators.md new file mode 100644 index 00000000..98eff076 --- /dev/null +++ b/docs/designers/language-basic-syntax/language-syntax-operators.md @@ -0,0 +1,64 @@ +# Operators + +## Basic + +Various basic operators can be applied directly to variable values. + +## Examples +```smarty +{$foo + 1} + +{$foo * $bar} + +{$foo->bar - $bar[1] * $baz->foo->bar() -3 * 7} + +{if ($foo + $bar.test % $baz * 134232 + 10 + $b + 10)} + ... +{/if} + +{$foo = $foo + $bar} +``` + +> **Note** +> +> Although Smarty can handle some very complex expressions and syntax, +> it is a good rule of thumb to keep the template syntax minimal and +> focused on presentation. If you find your template syntax getting too +> complex, it may be a good idea to move the bits that do not deal +> explicitly with presentation to PHP by way of plugins or modifiers. + +## Ternary +You can use the `?:` (or ternary) operator to test one expression and present the value +of the second or third expression, based on the result of the test. + +In other words: +```smarty +{$test ? "OK" : "FAIL"} +``` +will result in OK if `$test` is set to true, and in FAIL otherwise. + +There is also a shorthand `?:` operator: +```smarty +{$myVar ?: "empty"} +``` +will result in 'empty' if `$myVar` is not set or set to something that evaluates to false, such as an empty string. +If `$myVar` is set to something that evaluates to true, the value of `$myVar` is returned. So, the following will +return 'hello': +```smarty +{$myVar="hello"} +{$myVar ?: "empty"} +``` + +## Testing for null +If "something that evaluates to false" is to broad a test for you, you can use the `??` (or null coalescing) operator +to trigger only if the tested value is undefined or set to null. +```smarty +{$myVar ?? "empty"} +``` +will result in 'empty' if `$myVar` is not set or set to null. +If `$myVar` is set to something that evaluates to anything else, the value of `$myVar` is returned. So, the following will +return an empty string (''): +```smarty +{$myVar=""} +{$myVar ?: "this is not shown"} +```
\ No newline at end of file diff --git a/docs/designers/language-builtin-functions.md b/docs/designers/language-builtin-functions.md new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/docs/designers/language-builtin-functions.md diff --git a/docs/designers/language-builtin-functions/language-function-assign.md b/docs/designers/language-builtin-functions/language-function-assign.md index f5faa46d..518e3f7d 100644 --- a/docs/designers/language-builtin-functions/language-function-assign.md +++ b/docs/designers/language-builtin-functions/language-function-assign.md @@ -134,7 +134,6 @@ echo $smarty->getTemplateVars('foo'); The following functions can also *optionally* assign template variables: [`{capture}`](#language.function.capture), [`{include}`](#language.function.include), -[`{insert}`](#language.function.insert), [`{counter}`](#language.function.counter), [`{cycle}`](#language.function.cycle), [`{eval}`](#language.function.eval), diff --git a/docs/designers/language-builtin-functions/language-function-capture.md b/docs/designers/language-builtin-functions/language-function-capture.md index 657f077c..83f4d02d 100644 --- a/docs/designers/language-builtin-functions/language-function-capture.md +++ b/docs/designers/language-builtin-functions/language-function-capture.md @@ -27,12 +27,6 @@ is the value passed in the `name` attribute. If you do not supply the |---------|-----------------------------------------| | nocache | Disables caching of this captured block | -> **Note** -> -> Be careful when capturing [`{insert}`](#language.function.insert) -> output. If you have [`$caching`](#caching) enabled and you have -> [`{insert}`](#language.function.insert) commands that you expect to -> run within cached content, do not capture this content. ## Examples diff --git a/docs/designers/language-builtin-functions/language-function-foreach.md b/docs/designers/language-builtin-functions/language-function-foreach.md index 645d6c52..a0b7b588 100644 --- a/docs/designers/language-builtin-functions/language-function-foreach.md +++ b/docs/designers/language-builtin-functions/language-function-foreach.md @@ -166,7 +166,7 @@ looping over a PHP iterator instead of an array(). ```php <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; diff --git a/docs/designers/language-builtin-functions/language-function-if.md b/docs/designers/language-builtin-functions/language-function-if.md index c7be37a2..1372ea58 100644 --- a/docs/designers/language-builtin-functions/language-function-if.md +++ b/docs/designers/language-builtin-functions/language-function-if.md @@ -7,10 +7,6 @@ template engine. Every `{if}` must be paired with a matching `{/if}`. functions are recognized, such as *\|\|*, *or*, *&&*, *and*, *is_array()*, etc. -If security is enabled, only PHP functions from `$php_functions` property -of the security policy are allowed. See the -[Security](../../programmers/advanced-features/advanced-features-security.md) section for details. - The following is a list of recognized qualifiers, which must be separated from surrounding elements by spaces. Note that items listed in \[brackets\] are optional. PHP equivalents are shown where applicable. diff --git a/docs/designers/language-builtin-functions/language-function-include.md b/docs/designers/language-builtin-functions/language-function-include.md index d12a817e..54660cd5 100644 --- a/docs/designers/language-builtin-functions/language-function-include.md +++ b/docs/designers/language-builtin-functions/language-function-include.md @@ -183,5 +183,5 @@ current template. {include file="$style_dir/$module.$view.tpl"} ``` -See also [`{insert}`](./language-function-insert.md), [template resources](../../programmers/resources.md) and +See also [template resources](../../programmers/resources.md) and [componentized templates](../../appendixes/tips.md#componentized-templates). diff --git a/docs/designers/language-builtin-functions/language-function-insert.md b/docs/designers/language-builtin-functions/language-function-insert.md index 54f0729d..e69de29b 100644 --- a/docs/designers/language-builtin-functions/language-function-insert.md +++ b/docs/designers/language-builtin-functions/language-function-insert.md @@ -1,86 +0,0 @@ -# {insert} - -> **Note** -> -> `{insert}` tags are deprecated from Smarty, and should not be used. -> Put your PHP logic in PHP scripts or plugin functions instead. -> As of Smarty 3.1 the `{insert}` tags are only available from -> [SmartyBC](#bc). - -`{insert}` tags work much like [`{include}`](./language-function-include.md) -tags, except that `{insert}` tags are NOT cached when template -[caching](../../programmers/caching.md) is enabled. They will be executed on every -invocation of the template. - -| Attribute Name | Required | Description | -|----------------|----------|----------------------------------------------------------------------------------| -| name | Yes | The name of the insert function (insert_`name`) or insert plugin | -| assign | No | The name of the template variable the output will be assigned to | -| script | No | The name of the php script that is included before the insert function is called | -| \[var \...\] | No | variable to pass to insert function | - -## Examples - -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](../config-files.md)), and needs to call a function to get the -banner contents. - -```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 *} -``` - -In this example, we are using the name "getBanner" and passing the -parameters \#banner\_location\_id\# and \#site\_id\#. Smarty will look -for a function named insert\_getBanner() in your PHP application, -passing the values of \#banner\_location\_id\# and \#site\_id\# as the -first argument in an associative array. All {insert} function names in -your application must be prepended with "insert_" to remedy possible -function name-space conflicts. Your insert\_getBanner() function should -do something with the passed values and return the results. These -results are then displayed in the template in place of the {insert} tag. -In this example, Smarty would call this function: -insert_getBanner(array("lid" => "12345","sid" => "67890")); -and display the returned results in place of the {insert} tag. - -- If you supply the `assign` attribute, the output of the `{insert}` - tag will be assigned to this template variable instead of being - output to the template. - - > **Note** - > - > Assigning the output to a template variable isn't too useful with - > [caching](../../programmers/api-variables/variable-caching.md) enabled. - -- If you supply the `script` attribute, this php script will be - included (only once) before the `{insert}` function is executed. - This is the case where the insert function may not exist yet, and a - php script must be included first to make it work. - - The path can be either absolute, or relative to - [`$trusted_dir`](../../programmers/api-variables/variable-trusted-dir.md). If security is enabled, - then the script must be located in the `$trusted_dir` path of the - security policy. See the [Security](../../programmers/advanced-features/advanced-features-security.md) - section for details. - -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. - -If no PHP script can be found Smarty is looking for a corresponding -insert plugin. - -> **Note** -> -> It is possible to have portions of the template not cached. If you -> have [caching](../../programmers/api-variables/variable-caching.md) 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. - -See also [`{include}`](./language-function-include.md) diff --git a/docs/designers/language-builtin-functions/language-function-nocache.md b/docs/designers/language-builtin-functions/language-function-nocache.md index e6d8453f..7997ecfb 100644 --- a/docs/designers/language-builtin-functions/language-function-nocache.md +++ b/docs/designers/language-builtin-functions/language-function-nocache.md @@ -17,4 +17,4 @@ Today's date is The above code will output the current date on a cached page. -See also the [caching section](../../programmers/caching.md). +See also the [caching section](../../api/caching/basics.md). diff --git a/docs/designers/language-custom-functions/language-function-mailto.md b/docs/designers/language-custom-functions/language-function-mailto.md index bcb8b7d4..c32c2387 100644 --- a/docs/designers/language-custom-functions/language-function-mailto.md +++ b/docs/designers/language-custom-functions/language-function-mailto.md @@ -34,7 +34,7 @@ spiders to lift email addresses off of a site. <a href="mailto:me@example.com" >send me some mail</a> {mailto address="me@example.com" encode="javascript"} -<script type="text/javascript" language="javascript"> + <script> eval(unescape('%64%6f% ... snipped ...%61%3e%27%29%3b')) </script> @@ -51,7 +51,7 @@ spiders to lift email addresses off of a site. <a href="mailto:me@example.com" class="email">me@example.com</a> {mailto address="me@example.com" encode="javascript_charcode"} -<script type="text/javascript" language="javascript"> + <script> {document.write(String.fromCharCode(60,97, ... snipped ....60,47,97,62))} </script> ``` diff --git a/docs/designers/language-modifiers/index.md b/docs/designers/language-modifiers/index.md index c9aeef88..a384c95c 100644 --- a/docs/designers/language-modifiers/index.md +++ b/docs/designers/language-modifiers/index.md @@ -69,7 +69,7 @@ These parameters follow the modifier name and are separated by a `:` <select name="name_id"> {html_options output=$my_array|upper|truncate:20} </select> -``` +``` - Modifiers can be applied to any type of variables, including arrays and objects. @@ -96,26 +96,9 @@ These parameters follow the modifier name and are separated by a `:` > gives 9. To get the old result use parentheses like > `{(8+2)|count_characters}`. -- Modifiers are autoloaded from the - [`$plugins_dir`](../../programmers/api-variables/variable-plugins-dir.md) or can be registered - explicitly with the [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md) - function. The later is useful for sharing a function between php - scripts and smarty templates. - -- All php-functions can be used as modifiers implicitly, as - demonstrated in the example above. However, using php-functions as - modifiers has two little pitfalls: - - - First - sometimes the order of the function-parameters is not - the desirable one. Formatting `$foo` with - `{"%2.f"|sprintf:$foo}` actually works, but asks for the more - intuitive, like `{$foo|string_format:"%2.f"}` that is provided - by the Smarty distribution. - - - Secondly - if security is enabled, all php-functions that are to - be used as modifiers have to be declared trusted in the - `$modifiers` property of the security policy. See the - [Security](../../programmers/advanced-features/advanced-features-security.md) section for details. +- Custom modifiers can be registered + with the [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md) + function. See also [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md), [combining modifiers](../language-combining-modifiers.md). and [extending smarty with diff --git a/docs/designers/language-modifiers/language-modifier-from-charset.md b/docs/designers/language-modifiers/language-modifier-from-charset.md index bf4b4769..25c4d2d9 100644 --- a/docs/designers/language-modifiers/language-modifier-from-charset.md +++ b/docs/designers/language-modifiers/language-modifier-from-charset.md @@ -16,5 +16,5 @@ modifier](language-modifier-to-charset.md). > modifier should only be used in cases where the application cannot > anticipate that a certain string is required in another encoding. -See also [Charset Encoding](../../programmers/charset.md), [to_charset +See also [Configuring Smarty](../../api/configuring.md), [to_charset modifier](language-modifier-to-charset.md). diff --git a/docs/designers/language-modifiers/language-modifier-to-charset.md b/docs/designers/language-modifiers/language-modifier-to-charset.md index c0b00384..aa8cfd53 100644 --- a/docs/designers/language-modifiers/language-modifier-to-charset.md +++ b/docs/designers/language-modifiers/language-modifier-to-charset.md @@ -16,5 +16,5 @@ modifier](#language.modifier.from_charset). > modifier should only be used in cases where the application cannot > anticipate that a certain string is required in another encoding. -See also [Charset Encoding](../../programmers/charset.md), [from_charset +See also [Configuring Smarty](../../api/configuring.md), [from_charset modifier](language-modifier-from-charset.md). diff --git a/docs/designers/language-variables/language-assigned-variables.md b/docs/designers/language-variables/language-assigned-variables.md index bd356a2b..a358008f 100644 --- a/docs/designers/language-variables/language-assigned-variables.md +++ b/docs/designers/language-variables/language-assigned-variables.md @@ -7,7 +7,7 @@ Variables assigned from PHP are referenced by preceding them with a dollar ```php <?php - +use Smarty\Smarty; $smarty = new Smarty(); $smarty->assign('firstname', 'Doug'); diff --git a/docs/designers/language-variables/language-variables-smarty.md b/docs/designers/language-variables/language-variables-smarty.md index da543fb6..b6dff73a 100644 --- a/docs/designers/language-variables/language-variables-smarty.md +++ b/docs/designers/language-variables/language-variables-smarty.md @@ -66,8 +66,7 @@ difference. ## {$smarty.const} -You can access PHP constant values directly. See also [smarty -constants](../../programmers/smarty-constants.md). +You can access PHP constant values directly. ```php <?php diff --git a/docs/getting-started.md b/docs/getting-started.md index 2ffbbd11..0bab5aa0 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,7 +1,7 @@ # Getting started ## Requirements -Smarty can be run with PHP 7.1 to PHP 8.2. +Smarty can be run with PHP 7.2 to PHP 8.2. ## Installation Smarty can be installed with [Composer](https://getcomposer.org/). @@ -26,22 +26,21 @@ Here's how you create an instance of Smarty in your PHP scripts: <?php require 'vendor/autoload.php'; +use Smarty\Smarty; $smarty = new Smarty(); ``` Now that the library files are in place, it's time to set up the Smarty directories for your application. -Smarty requires four directories which are by default named - [`templates`](./programmers/api-variables/variable-template-dir.md), - [`configs`](./programmers/api-variables/variable-config-dir.md), - [`templates_c`](./programmers/api-variables/variable-compile-dir.md) - and - [`cache`](./programmers/api-variables/variable-cache-dir.md) - relative to the current working directory. +Smarty requires four directories which are by default named `templates`, `configs`, `templates_c` and `cache` +relative to the current working directory. The defaults can be changed as follows: + ```php +<?php +use Smarty\Smarty; $smarty = new Smarty(); $smarty->setTemplateDir('/some/template/dir'); $smarty->setConfigDir('/some/config/dir'); @@ -70,6 +69,8 @@ You can verify if your system has the correct access rights for these directories with [`testInstall()`](./programmers/api-functions/api-test-install.md): ```php +<?php +use Smarty\Smarty; $smarty = new Smarty(); $smarty->setTemplateDir('/some/template/dir'); $smarty->setConfigDir('/some/config/dir'); @@ -103,6 +104,7 @@ Now lets edit our php file. We'll create an instance of Smarty, require 'vendor/autoload.php'; +use Smarty\Smarty; $smarty = new Smarty(); $smarty->setTemplateDir('/web/www.example.com/guestbook/templates/'); @@ -140,7 +142,9 @@ the same vars, etc., we can do that in one place. ```php <?php -class Smarty_GuestBook extends Smarty { +use Smarty\Smarty; + +class My_GuestBook extends Smarty { public function __construct() { @@ -158,7 +162,7 @@ class Smarty_GuestBook extends Smarty { } ``` -Now, we can use `Smarty_GuestBook` instead of `Smarty` in our scripts: +Now, we can use `My_GuestBook` instead of `Smarty` in our scripts: ```php <?php $smarty = new Smarty_GuestBook(); diff --git a/docs/img/favicon.ico b/docs/img/favicon.ico Binary files differnew file mode 100644 index 00000000..aec1d8e3 --- /dev/null +++ b/docs/img/favicon.ico diff --git a/docs/index.md b/docs/index.md index cff5e490..0604f2a8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,8 +1,8 @@ -# Smarty 4 Documentation +# Smarty Documentation Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. It allows you to write **templates**, using **variables**, **modifiers**, **functions** and **comments**, like this: -```html +```smarty <h1>{$title|escape}</h1> <p> @@ -20,31 +20,11 @@ and 480 for $height, the result is: </p> ``` -## Introduction +## Getting Started +- [Getting Started](./getting-started.md) - [Philosophy](./philosophy.md) - or "Why do I need a template engine?" - [Features](./features.md) - or "Why do I want Smarty?" -- [Getting Started](./getting-started.md) - -## Smarty for template designers -- [Basic Syntax](designers/language-basic-syntax/index.md) -- [Variables](designers/language-variables/index.md) -- [Variable Modifiers](designers/language-modifiers/index.md) -- [Combining Modifiers](./designers/language-combining-modifiers.md) -- [Built-in Functions](designers/language-builtin-functions/index.md) -- [Custom Functions](designers/language-custom-functions/index.md) -- [Config Files](./designers/config-files.md) -- [Debugging Console](./designers/chapter-debugging-console.md) - -## Smarty for php developers -- [Charset Encoding](./programmers/charset.md) -- [Constants](./programmers/smarty-constants.md) -- [Smarty Class Variables](./programmers/api-variables.md) -- [Smarty Class Methods](./programmers/api-functions.md) -- [Caching](./programmers/caching.md) -- [Resources](./programmers/resources.md) -- [Advanced Features](./programmers/advanced-features.md) -- [Extending Smarty With Plugins](./programmers/plugins.md) -## Other +## Help - [Some random tips & tricks](./appendixes/tips.md) - [Troubleshooting](./appendixes/troubleshooting.md) diff --git a/docs/philosophy.md b/docs/philosophy.md index 34555c28..41bcfc8b 100644 --- a/docs/philosophy.md +++ b/docs/philosophy.md @@ -8,7 +8,7 @@ presentation. This is best described in a situation where the application programmer and the template designer play different roles, or in most cases are not the same person. -For example, let\'s say you are creating a web page that is displaying a +For example, let's say you are creating a web page that is displaying a newspaper article. - The article `$headline`, `$tagline`, `$author` and `$body` are diff --git a/docs/programmers/advanced-features.md b/docs/programmers/advanced-features.md deleted file mode 100644 index 60d4416b..00000000 --- a/docs/programmers/advanced-features.md +++ /dev/null @@ -1,14 +0,0 @@ -Advanced Features {#advanced.features} -================= - -## Table of contents - -- [Security](./advanced-features/advanced-features-security.md) -- [Changing settings by template](./advanced-features/advanced-features-template-settings.md) -- [Template Inheritance](./advanced-features/advanced-features-template-inheritance.md) -- [Streams](./advanced-features/advanced-features-streams.md) -- [Objects](./advanced-features/advanced-features-objects.md) -- [Static Classes](./advanced-features/advanced-features-static-classes.md) -- [Prefilters](./advanced-features/advanced-features-prefilters.md) -- [Postfilters](./advanced-features/advanced-features-postfilters.md) -- [Output Filters](./advanced-features/advanced-features-outputfilters.md) diff --git a/docs/programmers/advanced-features/advanced-features-objects.md b/docs/programmers/advanced-features/advanced-features-objects.md deleted file mode 100644 index b681945e..00000000 --- a/docs/programmers/advanced-features/advanced-features-objects.md +++ /dev/null @@ -1,99 +0,0 @@ -Objects {#advanced.features.objects} -======= - -Smarty allows access to PHP [objects](https://www.php.net/object) through -the templates. - -> **Note** -> -> When you assign/register objects to templates, be sure that all -> properties and methods accessed from the template are for presentation -> purposes only. It is very easy to inject application logic through -> objects, and this leads to poor designs that are difficult to manage. -> See the Best Practices section of the Smarty website. - -There are two ways to access them. - -- One way is to [register objects](#api.register.object) to the - template, then use access them via syntax similar to [custom - functions](#language.custom.functions). - -- The other way is to [`assign()`](#api.assign) objects to the - templates and access them much like any other assigned variable. - -The first method has a much nicer template syntax. It is also more -secure, as a registered object can be restricted to certain methods or -properties. However, **a registered object cannot be looped over or -assigned in arrays of objects**, etc. The method you choose will be -determined by your needs, but use the first method whenever possible to -keep template syntax to a minimum. - -If security is enabled, no private methods or functions can be accessed -(beginning with \'\_\'). If a method and property of the same name exist, -the method will be used. - -You can restrict the methods and properties that can be accessed by -listing them in an array as the third registration parameter. - -By default, parameters passed to objects through the templates are -passed the same way [custom functions](#language.custom.functions) get -them. An associative array is passed as the first parameter, and the -smarty object as the second. If you want the parameters passed one at a -time for each argument like traditional object parameter passing, set -the fourth registration parameter to FALSE. - -The optional fifth parameter has only effect with `format` being TRUE -and contains a list of methods that should be treated as blocks. That -means these methods have a closing tag in the template -(`{foobar->meth2}...{/foobar->meth2}`) and the parameters to the methods -have the same synopsis as the parameters for -[`block-function-plugins`](#plugins.block.functions): They get the four -parameters `$params`, `$content`, `$smarty` and `&$repeat` and they also -behave like block-function-plugins. - - - <?php - // the object - - class My_Object { - function meth1($params, $smarty_obj) { - return 'this is my meth1'; - } - } - - $myobj = new My_Object; - - // registering the object (will be by reference) - $smarty->registerObject('foobar',$myobj); - - // if we want to restrict access to certain methods or properties, list them - $smarty->registerObject('foobar',$myobj,array('meth1','meth2','prop1')); - - // if you want to use the traditional object parameter format, pass a boolean of false - $smarty->registerObject('foobar',$myobj,null,false); - - // We can also assign objects. assign_by_ref when possible. - $smarty->assign_by_ref('myobj', $myobj); - - $smarty->display('index.tpl'); - ?> - - - -And here\'s how to access your objects in `index.tpl`: - - - {* access our registered object *} - {foobar->meth1 p1='foo' p2=$bar} - - {* you can also assign the output *} - {foobar->meth1 p1='foo' p2=$bar assign='output'} - the output was {$output} - - {* access our assigned object *} - {$myobj->meth1('foo',$bar)} - - - -See also [`registerObject()`](#api.register.object) and -[`assign()`](#api.assign). diff --git a/docs/programmers/advanced-features/advanced-features-outputfilters.md b/docs/programmers/advanced-features/advanced-features-outputfilters.md deleted file mode 100644 index 393d7da2..00000000 --- a/docs/programmers/advanced-features/advanced-features-outputfilters.md +++ /dev/null @@ -1,43 +0,0 @@ -Output Filters {#advanced.features.outputfilters} -============== - -When the template is invoked via [`display()`](#api.display) or -[`fetch()`](#api.fetch), its output can be sent through one or more -output filters. This differs from -[`postfilters`](#advanced.features.postfilters) because postfilters -operate on compiled templates before they are saved to the disk, whereas -output filters operate on the template output when it is executed. - -Output filters can be either [registered](#api.register.filter) or -loaded from the [plugins directory](#variable.plugins.dir) by using the -[`loadFilter()`](#api.load.filter) method or by setting the -[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will -pass the template output as the first argument, and expect the function -to return the result of the processing. - - - <?php - // put this in your application - function protect_email($tpl_output, Smarty_Internal_Template $template) - { - $tpl_output = - preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!', - '$1%40$2', $tpl_output); - return $tpl_output; - } - - // register the outputfilter - $smarty->registerFilter("output","protect_email"); - $smarty->display("index.tpl'); - - // now any occurrence of an email address in the template output will have - // a simple protection against spambots - ?> - - - -See also [`registerFilter()`](#api.register.filter), -[`loadFilter()`](#api.load.filter), -[`$autoload_filters`](#variable.autoload.filters), -[postfilters](#advanced.features.postfilters) and -[`$plugins_dir`](#variable.plugins.dir). diff --git a/docs/programmers/advanced-features/advanced-features-postfilters.md b/docs/programmers/advanced-features/advanced-features-postfilters.md deleted file mode 100644 index d3bad546..00000000 --- a/docs/programmers/advanced-features/advanced-features-postfilters.md +++ /dev/null @@ -1,40 +0,0 @@ -Postfilters {#advanced.features.postfilters} -=========== - -Template postfilters are PHP functions that your templates are ran -through *after they are compiled*. Postfilters can be either -[registered](#api.register.filter) or loaded from the [plugins -directory](#variable.plugins.dir) by using the -[`loadFilter()`](#api.load.filter) function or by setting the -[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will -pass the compiled template code as the first argument, and expect the -function to return the result of the processing. - - - <?php - // put this in your application - function add_header_comment($tpl_source, Smarty_Internal_Template $template) - { - return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source; - } - - // register the postfilter - $smarty->registerFilter('post','add_header_comment'); - $smarty->display('index.tpl'); - ?> - - - -The postfilter above will make the compiled Smarty template `index.tpl` -look like: - - - <!-- Created by Smarty! --> - {* rest of template content... *} - - - -See also [`registerFilter()`](#api.register.filter), -[prefilters](#advanced.features.prefilters), -[outputfilters](#advanced.features.outputfilters), and -[`loadFilter()`](#api.load.filter). diff --git a/docs/programmers/advanced-features/advanced-features-prefilters.md b/docs/programmers/advanced-features/advanced-features-prefilters.md deleted file mode 100644 index 76229e63..00000000 --- a/docs/programmers/advanced-features/advanced-features-prefilters.md +++ /dev/null @@ -1,36 +0,0 @@ -Prefilters {#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 can be either [registered](#api.register.filter) or loaded -from the [plugins directory](#variable.plugins.dir) by using -[`loadFilter()`](#api.load.filter) function or by setting the -[`$autoload_filters`](#variable.autoload.filters) variable. - -Smarty will pass the template source code as the first argument, and -expect the function to return the resulting template source code. - -This will remove all the html comments in the template source. - - - <?php - // put this in your application - function remove_dw_comments($tpl_source, Smarty_Internal_Template $template) - { - return preg_replace("/<!--#.*-->/U",'',$tpl_source); - } - - // register the prefilter - $smarty->registerFilter('pre','remove_dw_comments'); - $smarty->display('index.tpl'); - ?> - - - -See also [`registerFilter()`](#api.register.filter), -[postfilters](#advanced.features.postfilters) and -[`loadFilter()`](#api.load.filter). diff --git a/docs/programmers/advanced-features/advanced-features-security.md b/docs/programmers/advanced-features/advanced-features-security.md deleted file mode 100644 index 730915f1..00000000 --- a/docs/programmers/advanced-features/advanced-features-security.md +++ /dev/null @@ -1,144 +0,0 @@ -Security {#advanced.features.security} -======== - -Security is good for situations when you have untrusted parties editing -the templates e.g. via ftp, and you want to reduce the risk of system -security compromises through the template language. - -The settings of the security policy are defined by properties of an -instance of the Smarty\_Security class. These are the possible settings: - -- `$secure_dir` is an array of template directories that are - considered secure. [`$template_dir`](#variable.template.dir) - considered secure implicitly. The default is an empty array. - -- `$trusted_dir` 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 - [`{insert}`](#language.function.insert.php). The default is an - empty array. - -- `$trusted_uri` is an array of regular expressions matching URIs that - are considered trusted. This security directive used by - [`{fetch}`](#language.function.fetch) and - [`{html_image}`](#language.function.html.image). URIs passed to - these functions are reduced to `{$PROTOCOL}://{$HOSTNAME}` to allow - simple regular expressions (without having to deal with edge cases - like authentication-tokens). - - The expression `'#https?://.*smarty.net$#i'` would allow accessing - the following URIs: - - - `http://smarty.net/foo` - - - `http://smarty.net/foo` - - - `http://www.smarty.net/foo` - - - `http://smarty.net/foo` - - - `https://foo.bar.www.smarty.net/foo/bla?blubb=1` - - but deny access to these URIs: - - - `http://smarty.com/foo` (not matching top-level domain \"com\") - - - `ftp://www.smarty.net/foo` (not matching protocol \"ftp\") - - - `http://www.smarty.net.otherdomain.com/foo` (not matching end of - domain \"smarty.net\") - -- `$static_classes` is an array of classes that are considered - trusted. The default is an empty array which allows access to all - static classes. To disable access to all static classes set - \$static\_classes = null. - -- `$php_functions` is an array of PHP functions that are considered - trusted and can be used from within template. To disable access to - all PHP functions set \$php\_functions = null. An empty array ( - \$php\_functions = array() ) will allow all PHP functions. The - default is array(\'isset\', \'empty\', \'count\', \'sizeof\', - \'in\_array\', \'is\_array\',\'time\',\'nl2br\'). - -- `$php_modifiers` is an array of PHP functions that are considered - trusted and can be used from within template as modifier. To disable - access to all PHP modifier set \$php\_modifier = null. An empty - array ( \$php\_modifier = array() ) will allow all PHP functions. - The default is array(\'escape\',\'count\'). - -- `$streams` is an array of streams that are considered trusted and - can be used from within template. To disable access to all streams - set \$streams = null. An empty array ( \$streams = array() ) will - allow all streams. The default is array(\'file\'). - -- `$allowed_modifiers` is an array of (registered / autoloaded) - modifiers that should be accessible to the template. If this array - is non-empty, only the herein listed modifiers may be used. This is - a whitelist. - -- `$disabled_modifiers` is an array of (registered / autoloaded) - modifiers that may not be accessible to the template. - -- `$allowed_tags` is a boolean flag which controls if constants can - function-, block and filter plugins that should be accessible to the - template. If this array is non-empty, only the herein listed - modifiers may be used. This is a whitelist. - -- `$disabled_tags` is an array of (registered / autoloaded) function-, - block and filter plugins that may not be accessible to the template. - -- `$allow_constants` is a boolean flag which controls if constants can - be accessed by the template. The default is \"true\". - -- `$allow_super_globals` is a boolean flag which controls if the PHP - super globals can be accessed by the template. The default is - \"true\". - -If security is enabled, no private methods, functions or properties of -static classes or assigned objects can be accessed (beginning with -\'\_\') by the template. - -To customize the security policy settings you can extend the -Smarty\_Security class or create an instance of it. - - - <?php - require 'Smarty.class.php'; - - class My_Security_Policy extends Smarty_Security { - // disable all PHP functions - public $php_functions = null; - // allow everthing as modifier - public $php_modifiers = array(); - } - $smarty = new Smarty(); - // enable security - $smarty->enableSecurity('My_Security_Policy'); - ?> - - - <?php - require 'Smarty.class.php'; - $smarty = new Smarty(); - $my_security_policy = new Smarty_Security($smarty); - // disable all PHP functions - $my_security_policy->php_functions = null; - // allow everthing as modifier - $my_security_policy->php_modifiers = array(); - // enable security - $smarty->enableSecurity($my_security_policy); - ?> - - - <?php - require 'Smarty.class.php'; - $smarty = new Smarty(); - // enable default security - $smarty->enableSecurity(); - ?> - -> **Note** -> -> Most security policy settings are only checked when the template gets -> compiled. For that reason you should delete all cached and compiled -> template files when you change your security settings. diff --git a/docs/programmers/advanced-features/advanced-features-static-classes.md b/docs/programmers/advanced-features/advanced-features-static-classes.md deleted file mode 100644 index 8ef79113..00000000 --- a/docs/programmers/advanced-features/advanced-features-static-classes.md +++ /dev/null @@ -1,27 +0,0 @@ -Static Classes {#advanced.features.static.classes} -============== - -You can directly access static classes. The syntax is the same as in -PHP. - -> **Note** -> -> Direct access to PHP classes is not recommended. This ties the -> underlying application code structure directly to the presentation, -> and also complicates template syntax. It is recommended to register -> plugins which insulate templates from PHP classes/objects. Use at your -> own discretion. See the Best Practices section of the Smarty website. - - - {assign var=foo value=myclass::BAR} <--- class constant BAR - - {assign var=foo value=myclass::method()} <--- method result - - {assign var=foo value=myclass::method1()->method2} <--- method chaining - - {assign var=foo value=myclass::$bar} <--- property bar of class myclass - - {assign var=foo value=$bar::method} <--- using Smarty variable bar as class name - - - diff --git a/docs/programmers/advanced-features/advanced-features-streams.md b/docs/programmers/advanced-features/advanced-features-streams.md deleted file mode 100644 index d6f7a0de..00000000 --- a/docs/programmers/advanced-features/advanced-features-streams.md +++ /dev/null @@ -1,15 +0,0 @@ -Streams {#advanced.features.streams} -======= - -You can also use streams to call variables. *{\$foo:bar}* will use the -*foo://bar* stream to get the template variable. - -Using a PHP stream for a template variable resource from within a -template. - - - {$foo:bar} - - - -See also [`Template Resources`](#resources) diff --git a/docs/programmers/advanced-features/advanced-features-template-inheritance.md b/docs/programmers/advanced-features/advanced-features-template-inheritance.md deleted file mode 100644 index ce47310c..00000000 --- a/docs/programmers/advanced-features/advanced-features-template-inheritance.md +++ /dev/null @@ -1,128 +0,0 @@ -Template Inheritance {#advanced.features.template.inheritance} -==================== - -Inheritance brings the concept of Object Oriented Programming to -templates, allowing you to define one (or more) base templates that can -be extended by child templates. Extending means that the child template -can override all or some of the parent named block areas. - -- The inheritance tree can be as deep as you want, meaning you can - extend a file that extends another one that extends another one and - so on. - -- The child templates can not define any content besides what\'s - inside [`{block}`](#language.function.block) tags they override. - Anything outside of [`{block}`](#language.function.block) tags will - be removed. - -- The content of [`{block}`](#language.function.block) tags from child - and parent templates can be merged by the `append` or `prepend` - [`{block}`](#language.function.block) tag option flags and - `{$smarty.block.parent}` or `{$smarty.block.child}` placeholders. - -- Template inheritance is a compile time process which creates a - single compiled template file. Compared to corresponding solutions - based on subtemplates included with the - [`{include}`](#language.function.include) tag it does have much - better performance when rendering. - -- The child template extends its parent defined with the - [`{extends}`](#language.function.extends) tag, which must be the - first line in the child template. Instead of using the - [`{extends}`](#language.function.extends) tags in the template files - you can define the whole template inheritance tree in the PHP script - when you are calling [`fetch()`](#api.fetch) or - [`display()`](#api.display) with the `extends:` template resource - type. The later provides even more flexibility. - -> **Note** -> -> When `$compile_check` is enabled, all files in the inheritance tree -> are checked for modifications upon each invocation. You may want to -> disable `$compile_check` on production servers for this reason. - -> **Note** -> -> If you have a subtemplate which is included with -> [`{include}`](#language.function.include) and it contains -> [`{block}`](#language.function.block) areas it works only if the -> [`{include}`](#language.function.include) itself is called from within -> a surrounding [`{block}`](#language.function.block). In the final -> parent template you may need a dummy -> [`{block}`](#language.function.block) for it. - -layout.tpl (parent) - - - <html> - <head> - <title>{block name=title}Default Page Title{/block}</title> - {block name=head}{/block} - </head> - <body> - {block name=body}{/block} - </body> - </html> - - - -myproject.tpl (child) - - - {extends file='layout.tpl'} - {block name=head} - <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> - <script src="/js/mypage.js"></script> - {/block} - - - - -mypage.tpl (grandchild) - - - {extends file='myproject.tpl'} - {block name=title}My Page Title{/block} - {block name=head} - <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> - <script src="/js/mypage.js"></script> - {/block} - {block name=body}My HTML Page Body goes here{/block} - - - -To render the above use - - - $smarty->display('mypage.tpl'); - -The resulting output is - - - <html> - <head> - <title>My Page Title</title> - <link href="/css/mypage.css" rel="stylesheet" type="text/css"/> - <script src="/js/mypage.js"></script> - </head> - <body> - My HTML Page Body goes here - </body> - </html> - -Instead of using [`{extends}`](#language.function.extends) tags in the -template files you can define the inheritance tree in your PHP script by -using the [`extends:` resource](#resources.extends) type. - -The code below will return same result as the example above. - - - <?php - $smarty->display('extends:layout.tpl|myproject.tpl|mypage.tpl'); - ?> - - - -See also [`{block}`](#language.function.block), -[`{extends}`](#language.function.extends) and [`extends:` -resource](#resources.extends) diff --git a/docs/programmers/advanced-features/advanced-features-template-settings.md b/docs/programmers/advanced-features/advanced-features-template-settings.md deleted file mode 100644 index b06430ff..00000000 --- a/docs/programmers/advanced-features/advanced-features-template-settings.md +++ /dev/null @@ -1,32 +0,0 @@ -Changing settings by template {#advanced.features.template.settings} -============================= - -Normally you configure the Smarty settings by modifying the -[`Smarty class variables`](#api.variables). Furthermore you can register -plugins, filters etc. with [`Smarty functions`](#api.functions). -Modifications done to the Smarty object will be global for all -templates. - -However the Smarty class variables and functions can be accessed or -called by individual template objects. Modification done to a template -object will apply only for that template and its included subtemplates. - - - <?php - $tpl = $smarty->createTemplate('index.tpl); - $tpl->cache_lifetime = 600; - //or - $tpl->setCacheLifetime(600); - $smarty->display($tpl); - ?> - - - - - <?php - $tpl = $smarty->createTemplate('index.tpl); - $tpl->registerPlugin('modifier','mymodifier'); - $smarty->display($tpl); - ?> - - diff --git a/docs/programmers/api-functions.md b/docs/programmers/api-functions.md deleted file mode 100644 index 6f120fa9..00000000 --- a/docs/programmers/api-functions.md +++ /dev/null @@ -1,64 +0,0 @@ -Smarty Class Methods {#api.functions} -==================== - -## Table of contents - -- [addConfigDir()](./api-functions/api-add-config-dir.md) — add a directory to the list of directories where config files are stored -- [addPluginsDir()](./api-functions/api-add-plugins-dir.md) — add a directory to the list of directories where plugins are stored -- [addTemplateDir()](./api-functions/api-add-template-dir.md) — add a directory to the list of directories where templates are stored -- [append()](./api-functions/api-append.md) — append an element to an assigned array -- [appendByRef()](./api-functions/api-append-by-ref.md) — append values by reference -- [assign()](./api-functions/api-assign.md) — assign variables/objects to the templates -- [assignByRef()](./api-functions/api-assign-by-ref.md) — assign values by reference -- [clearAllAssign()](./api-functions/api-clear-all-assign.md) — clears the values of all assigned variables -- [clearAllCache()](./api-functions/api-clear-all-cache.md) — clears the entire template cache -- [clearAssign()](./api-functions/api-clear-assign.md) — clears the value of an assigned variable -- [clearCache()](./api-functions/api-clear-cache.md) — clears the cache for a specific template -- [clearCompiledTemplate()](./api-functions/api-clear-compiled-tpl.md) — clears the compiled version of the specified template resource -- [clearConfig()](./api-functions/api-clear-config.md) — clears assigned config variables -- [compileAllConfig()](./api-functions/api-compile-all-config.md) — compiles all known config files -- [compileAllTemplates()](./api-functions/api-compile-all-templates.md) — compiles all known templates -- [configLoad()](./api-functions/api-config-load.md) — loads config file data and assigns it to the template -- [createData()](./api-functions/api-create-data.md) — creates a data object -- [createTemplate()](./api-functions/api-create-template.md) — returns a template object -- [disableSecurity()](./api-functions/api-disable-security.md) — disables template security -- [display()](./api-functions/api-display.md) — displays the template -- [enableSecurity()](./api-functions/api-enable-security.md) — enables template security -- [fetch()](./api-functions/api-fetch.md) — returns the template output -- [getCacheDir()](./api-functions/api-get-cache-dir.md) — return the directory where the rendered template's output is stored -- [getCompileDir()](./api-functions/api-get-compile-dir.md) — returns the directory where compiled templates are stored -- [getConfigDir()](./api-functions/api-get-config-dir.md) — return the directory where config files are stored -- [getConfigVars()](./api-functions/api-get-config-vars.md) — returns the given loaded config variable value -- [getPluginsDir()](./api-functions/api-get-plugins-dir.md) — return the directory where plugins are stored -- [getRegisteredObject()](./api-functions/api-get-registered-object.md) — returns a reference to a registered object -- [getTags()](./api-functions/api-get-tags.md) — return tags used by template -- [getTemplateDir()](./api-functions/api-get-template-dir.md) — return the directory where templates are stored -- [getTemplateVars()](./api-functions/api-get-template-vars.md) — returns assigned variable value(s) -- [isCached()](./api-functions/api-is-cached.md) — returns true if there is a valid cache for this template -- [loadFilter()](./api-functions/api-load-filter.md) — load a filter plugin -- [muteExpectedErrors()](./api-functions/api-mute-expected-errors.md) — mutes expected warnings and notices deliberately generated by Smarty -- [registerCacheResource()](./api-functions/api-register-cacheresource.md) — dynamically register CacheResources -- [registerClass()](./api-functions/api-register-class.md) — register a class for use in the templates -- [registerDefaultPluginHandler()](./api-functions/api-register-default-plugin-handler.md) — register a function which gets called on undefined tags -- [registerFilter()](./api-functions/api-register-filter.md) — dynamically register filters -- [registerPlugin()](./api-functions/api-register-plugin.md) — dynamically register plugins -- [registerObject()](./api-functions/api-register-object.md) — register an object for use in the templates -- [registerResource()](./api-functions/api-register-resource.md) — dynamically register resources -- [setCacheDir()](./api-functions/api-set-cache-dir.md) — set the directory where the rendered template's output is stored -- [setCompileDir()](./api-functions/api-set-compile-dir.md) — set the directory where compiled templates are stored -- [setConfigDir()](./api-functions/api-set-config-dir.md) — set the directories where config files are stored -- [setPluginsDir()](./api-functions/api-set-plugins-dir.md) — set the directories where plugins are stored -- [setTemplateDir()](./api-functions/api-set-template-dir.md) — set the directories where templates are stored -- [templateExists()](./api-functions/api-template-exists.md) — checks whether the specified template exists -- [unregisterCacheResource()](./api-functions/api-unregister-cacheresource.md) — dynamically unregister a CacheResource plugin -- [unregisterFilter()](./api-functions/api-unregister-filter.md) — dynamically unregister a filter -- [unregisterPlugin()](./api-functions/api-unregister-plugin.md) — dynamically unregister plugins -- [unregisterObject()](./api-functions/api-unregister-object.md) — dynamically unregister an object -- [unregisterResource()](./api-functions/api-unregister-resource.md) — dynamically unregister a resource plugin -- [testInstall()](./api-functions/api-test-install.md) — checks Smarty installation - -> **Note** -> -> See -> [`Changing settings by template`](./advanced-features/advanced-features-template-settings.md) -> section for how to use the functions for individual templates. diff --git a/docs/programmers/api-functions/add-extension.md b/docs/programmers/api-functions/add-extension.md new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/docs/programmers/api-functions/add-extension.md diff --git a/docs/programmers/api-functions/api-add-config-dir.md b/docs/programmers/api-functions/api-add-config-dir.md deleted file mode 100644 index c3a05228..00000000 --- a/docs/programmers/api-functions/api-add-config-dir.md +++ /dev/null @@ -1,49 +0,0 @@ -addConfigDir() - -add a directory to the list of directories where config files are stored - -Description -=========== - -Smarty - -addConfigDir - -string\|array - -config\_dir - -string - -key - - - <?php - - // add directory where config files are stored - $smarty->addConfigDir('./config_1'); - - // add directory where config files are stored and specify array-key - $smarty->addConfigDir('./config_1', 'one'); - - // add multiple directories where config files are stored and specify array-keys - $smarty->addTemplateDir(array( - 'two' => './config_2', - 'three' => './config_3', - )); - - // view the template dir chain - var_dump($smarty->getConfigDir()); - - // chaining of method calls - $smarty->setConfigDir('./config') - ->addConfigDir('./config_1', 'one') - ->addConfigDir('./config_2', 'two'); - - ?> - - - -See also [`getConfigDir()`](#api.get.config.dir), -[`setConfigDir()`](#api.set.config.dir) and -[`$config_dir`](#variable.config.dir). diff --git a/docs/programmers/api-functions/api-add-template-dir.md b/docs/programmers/api-functions/api-add-template-dir.md deleted file mode 100644 index e0d24564..00000000 --- a/docs/programmers/api-functions/api-add-template-dir.md +++ /dev/null @@ -1,49 +0,0 @@ -addTemplateDir() - -add a directory to the list of directories where templates are stored - -Description -=========== - -Smarty - -addTemplateDir - -string\|array - -template\_dir - -string - -key - - - <?php - - // add directory where templates are stored - $smarty->addTemplateDir('./templates_1'); - - // add directory where templates are stored and specify array-key - $smarty->addTemplateDir('./templates_1', 'one'); - - // add multiple directories where templates are stored and specify array-keys - $smarty->addTemplateDir(array( - 'two' => './templates_2', - 'three' => './templates_3', - )); - - // view the template dir chain - var_dump($smarty->getTemplateDir()); - - // chaining of method calls - $smarty->setTemplateDir('./templates') - ->addTemplateDir('./templates_1', 'one') - ->addTemplateDir('./templates_2', 'two'); - - ?> - - - -See also [`getTemplateDir()`](#api.get.template.dir), -[`setTemplateDir()`](#api.set.template.dir) and -[`$template_dir`](#variable.template.dir). diff --git a/docs/programmers/api-functions/api-append-by-ref.md b/docs/programmers/api-functions/api-append-by-ref.md deleted file mode 100644 index cd396d9c..00000000 --- a/docs/programmers/api-functions/api-append-by-ref.md +++ /dev/null @@ -1,46 +0,0 @@ -appendByRef() - -append values by reference - -Description -=========== - -void - -appendByRef - -string - -varname - -mixed - -var - -bool - -merge - -This is used to [`append()`](#api.append) values to the templates by -reference. - -> **Note** -> -> With the introduction of PHP5, `appendByRef()` is not necessary for -> most intents and purposes. `appendByRef()` is useful if you want a PHP -> array index value to be affected by its reassignment from a template. -> Assigned object properties behave this way by default. - -NOTE.PARAMETER.MERGE - - - <?php - // appending name/value pairs - $smarty->appendByRef('Name', $myname); - $smarty->appendByRef('Address', $address); - ?> - - - -See also [`append()`](#api.append), [`assign()`](#api.assign) and -[`getTemplateVars()`](#api.get.template.vars). diff --git a/docs/programmers/api-functions/api-append.md b/docs/programmers/api-functions/api-append.md index b9458641..d9acff84 100644 --- a/docs/programmers/api-functions/api-append.md +++ b/docs/programmers/api-functions/api-append.md @@ -56,6 +56,5 @@ NOTE.PARAMETER.MERGE -See also [`appendByRef()`](#api.append.by.ref), -[`assign()`](#api.assign) and +See also [`assign()`](#api.assign) and [`getTemplateVars()`](#api.get.template.vars) diff --git a/docs/programmers/api-functions/api-assign-by-ref.md b/docs/programmers/api-functions/api-assign-by-ref.md deleted file mode 100644 index 7c42b483..00000000 --- a/docs/programmers/api-functions/api-assign-by-ref.md +++ /dev/null @@ -1,42 +0,0 @@ -assignByRef() - -assign values by reference - -Description -=========== - -void - -assignByRef - -string - -varname - -mixed - -var - -This is used to [`assign()`](#api.assign) values to the templates by -reference. - -> **Note** -> -> With the introduction of PHP5, `assignByRef()` is not necessary for -> most intents and purposes. `assignByRef()` is useful if you want a PHP -> array index value to be affected by its reassignment from a template. -> Assigned object properties behave this way by default. - - - <?php - // passing name/value pairs - $smarty->assignByRef('Name', $myname); - $smarty->assignByRef('Address', $address); - ?> - - - -See also [`assign()`](#api.assign), -[`clearAllAssign()`](#api.clear.all.assign), [`append()`](#api.append), -[`{assign}`](#language.function.assign) and -[`getTemplateVars()`](#api.get.template.vars). diff --git a/docs/programmers/api-functions/api-assign.md b/docs/programmers/api-functions/api-assign.md index c3b9985d..31f6a150 100644 --- a/docs/programmers/api-functions/api-assign.md +++ b/docs/programmers/api-functions/api-assign.md @@ -78,7 +78,6 @@ To access more complex array assignments see [`{foreach}`](#language.function.foreach) and [`{section}`](#language.function.section) -See also [`assignByRef()`](#api.assign.by.ref), -[`getTemplateVars()`](#api.get.template.vars), +See also [`getTemplateVars()`](#api.get.template.vars), [`clearAssign()`](#api.clear.assign), [`append()`](#api.append) and [`{assign}`](#language.function.assign) diff --git a/docs/programmers/api-functions/api-compile-all-config.md b/docs/programmers/api-functions/api-compile-all-config.md index a102fc97..35497d9a 100644 --- a/docs/programmers/api-functions/api-compile-all-config.md +++ b/docs/programmers/api-functions/api-compile-all-config.md @@ -50,7 +50,7 @@ parameters: <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; // force compilation of all config files diff --git a/docs/programmers/api-functions/api-compile-all-templates.md b/docs/programmers/api-functions/api-compile-all-templates.md index 53a021da..2be22eef 100644 --- a/docs/programmers/api-functions/api-compile-all-templates.md +++ b/docs/programmers/api-functions/api-compile-all-templates.md @@ -60,7 +60,7 @@ parameters: <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; // force compilation of all template files diff --git a/docs/programmers/api-functions/api-create-data.md b/docs/programmers/api-functions/api-create-data.md index 7e083776..dc03ad94 100644 --- a/docs/programmers/api-functions/api-create-data.md +++ b/docs/programmers/api-functions/api-create-data.md @@ -30,7 +30,7 @@ be used to control which variables are seen by which templates. <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; // create data object with its private variable scope diff --git a/docs/programmers/api-functions/api-create-template.md b/docs/programmers/api-functions/api-create-template.md index 5129406d..097b7df9 100644 --- a/docs/programmers/api-functions/api-create-template.md +++ b/docs/programmers/api-functions/api-create-template.md @@ -80,7 +80,7 @@ following parameters: <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; // create template object with its private variable scope diff --git a/docs/programmers/api-functions/api-display.md b/docs/programmers/api-functions/api-display.md index 59726195..ced7513f 100644 --- a/docs/programmers/api-functions/api-display.md +++ b/docs/programmers/api-functions/api-display.md @@ -31,7 +31,9 @@ PARAMETER.COMPILEID <?php - include(SMARTY_DIR.'Smarty.class.php'); + + use Smarty\Smarty; + $smarty = new Smarty(); $smarty->setCaching(true); diff --git a/docs/programmers/api-functions/api-fetch.md b/docs/programmers/api-functions/api-fetch.md index 6da05bd0..491c28d4 100644 --- a/docs/programmers/api-functions/api-fetch.md +++ b/docs/programmers/api-functions/api-fetch.md @@ -30,7 +30,7 @@ PARAMETER.COMPILEID <?php - include('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty; $smarty->setCaching(true); diff --git a/docs/programmers/api-functions/api-get-cache-dir.md b/docs/programmers/api-functions/api-get-cache-dir.md deleted file mode 100644 index 9e55d8d0..00000000 --- a/docs/programmers/api-functions/api-get-cache-dir.md +++ /dev/null @@ -1,23 +0,0 @@ -getCacheDir() - -return the directory where the rendered template\'s output is stored - -Description -=========== - -string - -getCacheDir - - - <?php - - // get directory where compiled templates are stored - $cacheDir = $smarty->getCacheDir(); - - ?> - - - -See also [`setCacheDir()`](#api.set.cache.dir) and -[`$cache_dir`](#variable.cache.dir). diff --git a/docs/programmers/api-functions/api-get-compile-dir.md b/docs/programmers/api-functions/api-get-compile-dir.md deleted file mode 100644 index 3bfae730..00000000 --- a/docs/programmers/api-functions/api-get-compile-dir.md +++ /dev/null @@ -1,23 +0,0 @@ -getCompileDir() - -returns the directory where compiled templates are stored - -Description -=========== - -string - -getCompileDir - - - <?php - - // get directory where compiled templates are stored - $compileDir = $smarty->getCompileDir(); - - ?> - - - -See also [`setCompileDir()`](#api.set.compile.dir) and -[`$compile_dir`](#variable.compile.dir). diff --git a/docs/programmers/api-functions/api-get-tags.md b/docs/programmers/api-functions/api-get-tags.md deleted file mode 100644 index 7729b468..00000000 --- a/docs/programmers/api-functions/api-get-tags.md +++ /dev/null @@ -1,40 +0,0 @@ -getTags() - -return tags used by template - -Description -=========== - -string - -getTags - -object - -template - -This function returns an array of tagname/attribute pairs for all tags -used by the template. It uses the following parameters: - -- `template` is the template object. - -> **Note** -> -> This function is experimental. - - - <?php - include('Smarty.class.php'); - $smarty = new Smarty; - - // create template object - $tpl = $smarty->createTemplate('index.tpl'); - - // get tags - $tags = $smarty->getTags($tpl); - - print_r($tags); - - ?> - - diff --git a/docs/programmers/api-functions/api-get-template-dir.md b/docs/programmers/api-functions/api-get-template-dir.md deleted file mode 100644 index 42c75908..00000000 --- a/docs/programmers/api-functions/api-get-template-dir.md +++ /dev/null @@ -1,40 +0,0 @@ -getTemplateDir() - -return the directory where templates are stored - -Description -=========== - -string\|array - -getTemplateDir - -string - -key - - - <?php - - // set some template directories - $smarty->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 - - ?> - - - -See also [`setTemplateDir()`](#api.set.template.dir), -[`addTemplateDir()`](#api.add.template.dir) and -[`$template_dir`](#variable.template.dir). diff --git a/docs/programmers/api-functions/api-is-cached.md b/docs/programmers/api-functions/api-is-cached.md index 0c41bf04..d9d3057f 100644 --- a/docs/programmers/api-functions/api-is-cached.md +++ b/docs/programmers/api-functions/api-is-cached.md @@ -22,8 +22,8 @@ string compile\_id - This only works if [`$caching`](#variable.caching) is set to one of - `Smarty::CACHING_LIFETIME_CURRENT` or - `Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching + `\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or + `\Smarty\Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching section](#caching) for more info. - You can also pass a `$cache_id` as an optional second parameter in diff --git a/docs/programmers/api-functions/api-load-filter.md b/docs/programmers/api-functions/api-load-filter.md index 19286ee3..e2738b0c 100644 --- a/docs/programmers/api-functions/api-load-filter.md +++ b/docs/programmers/api-functions/api-load-filter.md @@ -18,7 +18,7 @@ string name The first argument specifies the type of the filter to load and can be -one of the following: `pre`, `post` or `output`. The second argument +one of the following: `variable`, `pre`, `post` or `output`. The second argument specifies the `name` of the filter plugin. @@ -37,6 +37,5 @@ specifies the `name` of the filter plugin. -See also [`registerFilter()`](#api.register.filter), -[`$autoload_filters`](#variable.autoload.filters) and [advanced +See also [`registerFilter()`](#api.register.filter) and [advanced features](#advanced.features). diff --git a/docs/programmers/api-functions/api-mute-expected-errors.md b/docs/programmers/api-functions/api-mute-expected-errors.md index 626288ea..ac84a643 100644 --- a/docs/programmers/api-functions/api-mute-expected-errors.md +++ b/docs/programmers/api-functions/api-mute-expected-errors.md @@ -15,7 +15,7 @@ handler merely inspects `$errno` and `$errfile` to determine if the given error was produced deliberately and must be ignored, or should be passed on to the next error handler. -`Smarty::unmuteExpectedErrors()` removes the current error handler. +`\Smarty\Smarty::unmuteExpectedErrors()` removes the current error handler. Please note, that if you\'ve registered any custom error handlers after the muteExpectedErrors() call, the unmute will not remove Smarty\'s muting error handler, but the one registered last. diff --git a/docs/programmers/api-functions/api-register-cacheresource.md b/docs/programmers/api-functions/api-register-cacheresource.md index 60ae6030..62609149 100644 --- a/docs/programmers/api-functions/api-register-cacheresource.md +++ b/docs/programmers/api-functions/api-register-cacheresource.md @@ -31,7 +31,7 @@ how to create custom CacheResources. <?php - $smarty->registerCacheResource('mysql', new Smarty_CacheResource_Mysql()); + $smarty->registerCacheResource('mysql', new My_CacheResource_Mysql()); ?> diff --git a/docs/programmers/api-functions/api-register-class.md b/docs/programmers/api-functions/api-register-class.md index ee339cad..d0156d51 100644 --- a/docs/programmers/api-functions/api-register-class.md +++ b/docs/programmers/api-functions/api-register-class.md @@ -24,6 +24,7 @@ otherwise. If security is enabled, classes registered with <?php + use Smarty\Smarty; class Bar { $property = "hello world"; @@ -44,12 +45,14 @@ otherwise. If security is enabled, classes registered with <?php + use Smarty\Smarty; + namespace my\php\application { class Bar { $property = "hello world"; } } - + $smarty = new Smarty(); $smarty->registerClass("Foo", "\my\php\application\Bar"); diff --git a/docs/programmers/api-functions/api-register-default-plugin-handler.md b/docs/programmers/api-functions/api-register-default-plugin-handler.md index 03547df7..61ac4761 100644 --- a/docs/programmers/api-functions/api-register-default-plugin-handler.md +++ b/docs/programmers/api-functions/api-register-default-plugin-handler.md @@ -25,7 +25,7 @@ plugin types. <?php - + use Smarty\Smarty; $smarty = new Smarty(); $smarty->registerDefaultPluginHandler('my_plugin_handler'); @@ -37,7 +37,7 @@ plugin types. * @param string $name name of the undefined tag * @param string $type tag type (e.g. Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK, Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_MODIFIER, Smarty::PLUGIN_MODIFIERCOMPILER) - * @param Smarty_Internal_Template $template template object + * @param \Smarty\Template\ $template template object * @param string &$callback returned function name * @param string &$script optional returned script filepath if function is external * @param bool &$cacheable true by default, set to false if plugin is not cachable (Smarty >= 3.1.8) diff --git a/docs/programmers/api-functions/api-register-filter.md b/docs/programmers/api-functions/api-register-filter.md index fd91d266..4a2aa4b0 100644 --- a/docs/programmers/api-functions/api-register-filter.md +++ b/docs/programmers/api-functions/api-register-filter.md @@ -38,8 +38,7 @@ filters](#advanced.features.outputfilters) for more information on how to set up an output filter function. See also [`unregisterFilter()`](#api.unregister.filter), -[`loadFilter()`](#api.load.filter), -[`$autoload_filters`](#variable.autoload.filters), [template pre +[`loadFilter()`](#api.load.filter), [template pre filters](#advanced.features.prefilters) [template post filters](#advanced.features.postfilters) [template output filters](#advanced.features.outputfilters) section. diff --git a/docs/programmers/api-functions/api-register-plugin.md b/docs/programmers/api-functions/api-register-plugin.md index 6eb43381..51342b8e 100644 --- a/docs/programmers/api-functions/api-register-plugin.md +++ b/docs/programmers/api-functions/api-register-plugin.md @@ -32,9 +32,9 @@ cache\_attrs This method registers functions or methods defined in your script as plugin. It uses the following parameters: -- `cacheable` and `cache_attrs` can be omitted in most cases. See +- `cacheable` can be omitted in most cases. See [controlling cacheability of plugins output](#caching.cacheable) on - how to use them properly. + how to use this properly. <!-- --> diff --git a/docs/programmers/api-functions/api-register-resource.md b/docs/programmers/api-functions/api-register-resource.md index ca400546..774452bf 100644 --- a/docs/programmers/api-functions/api-register-resource.md +++ b/docs/programmers/api-functions/api-register-resource.md @@ -37,7 +37,7 @@ information on how to setup a function for fetching templates. <?php - $smarty->registerResource('mysql', new Smarty_Resource_Mysql()); + $smarty->registerResource('mysql', new My_Resource_Mysql()); ?> diff --git a/docs/programmers/api-functions/api-set-cache-dir.md b/docs/programmers/api-functions/api-set-cache-dir.md deleted file mode 100644 index 7f7c4b60..00000000 --- a/docs/programmers/api-functions/api-set-cache-dir.md +++ /dev/null @@ -1,32 +0,0 @@ -setCacheDir() - -set the directory where the rendered template\'s output is stored - -Description -=========== - -Smarty - -setCacheDir - -string - -cache\_dir - - - <?php - - // set directory where rendered template's output is stored - $smarty->setCacheDir('./cache'); - - // chaining of method calls - $smarty->setTemplateDir('./templates') - ->setCompileDir('./templates_c') - ->setCacheDir('./cache'); - - ?> - - - -See also [`getCacheDir()`](#api.get.cache.dir) and -[`$cache_dir`](#variable.cache.dir). diff --git a/docs/programmers/api-functions/api-set-compile-dir.md b/docs/programmers/api-functions/api-set-compile-dir.md deleted file mode 100644 index bfeb55a5..00000000 --- a/docs/programmers/api-functions/api-set-compile-dir.md +++ /dev/null @@ -1,32 +0,0 @@ -setCompileDir() - -set the directory where compiled templates are stored - -Description -=========== - -Smarty - -setCompileDir - -string - -compile\_dir - - - <?php - - // set directory where compiled templates are stored - $smarty->setCompileDir('./templates_c'); - - // chaining of method calls - $smarty->setTemplateDir('./templates') - ->setCompileDir('./templates_c') - ->setCacheDir('./cache'); - - ?> - - - -See also [`getCompileDir()`](#api.get.compile.dir) and -[`$compile_dir`](#variable.compile.dir). diff --git a/docs/programmers/api-functions/api-set-config-dir.md b/docs/programmers/api-functions/api-set-config-dir.md deleted file mode 100644 index 97a6ae97..00000000 --- a/docs/programmers/api-functions/api-set-config-dir.md +++ /dev/null @@ -1,47 +0,0 @@ -setConfigDir() - -set the directories where config files are stored - -Description -=========== - -Smarty - -setConfigDir - -string\|array - -config\_dir - - - <?php - - // set a single directory where the config files are stored - $smarty->setConfigDir('./config'); - - // view the config dir chain - var_dump($smarty->getConfigDir()); - - // set multiple directorÃes where config files are stored - $smarty->setConfigDir(array( - 'one' => './config', - 'two' => './config_2', - 'three' => './config_3', - )); - - // view the config dir chain - var_dump($smarty->getConfigDir()); - - // chaining of method calls - $smarty->setTemplateDir('./templates') - ->setConfigDir('./config') - ->setCompileDir('./templates_c') - ->setCacheDir('./cache'); - - ?> - - - -See also [`getConfigDir()`](#api.get.config.dir), -[`addConfigDir()`](#api.add.config.dir) and -[`$config_dir`](#variable.config.dir). diff --git a/docs/programmers/api-functions/api-set-template-dir.md b/docs/programmers/api-functions/api-set-template-dir.md deleted file mode 100644 index 2de23309..00000000 --- a/docs/programmers/api-functions/api-set-template-dir.md +++ /dev/null @@ -1,46 +0,0 @@ -setTemplateDir() - -set the directories where templates are stored - -Description -=========== - -Smarty - -setTemplateDir - -string\|array - -template\_dir - - - <?php - - // set a single directory where the templates are stored - $smarty->setTemplateDir('./cache'); - - // view the template dir chain - var_dump($smarty->getTemplateDir()); - - // set multiple directorÃes where templates are stored - $smarty->setTemplateDir(array( - 'one' => './templates', - 'two' => './templates_2', - 'three' => './templates_3', - )); - - // view the template dir chain - var_dump($smarty->getTemplateDir()); - - // chaining of method calls - $smarty->setTemplateDir('./templates') - ->setCompileDir('./templates_c') - ->setCacheDir('./cache'); - - ?> - - - -See also [`getTemplateDir()`](#api.get.template.dir), -[`addTemplateDir()`](#api.add.template.dir) and -[`$template_dir`](#variable.template.dir). diff --git a/docs/programmers/api-functions/api-template-exists.md b/docs/programmers/api-functions/api-template-exists.md deleted file mode 100644 index 07f61b12..00000000 --- a/docs/programmers/api-functions/api-template-exists.md +++ /dev/null @@ -1,59 +0,0 @@ -templateExists() - -checks whether the specified template exists - -Description -=========== - -bool - -templateExists - -string - -template - -It can accept either a path to the template on the filesystem or a -resource string specifying the template. - -This example uses `$_GET['page']` to -[`{include}`](#language.function.include) a content template. If the -template does not exist then an error page is displayed instead. First -the `page_container.tpl` - - - <html> - <head><title>{$title}</title></head> - <body> - {include file='page_top.tpl'} - - {* include middle content page *} - {include file=$content_template} - - {include file='page_footer.tpl'} - </body> - - - -And the php script - - - <?php - - // set the filename eg index.inc.tpl - $mid_template = $_GET['page'].'.inc.tpl'; - - if( !$smarty->templateExists($mid_template) ){ - $mid_template = 'page_not_found.tpl'; - } - $smarty->assign('content_template', $mid_template); - - $smarty->display('page_container.tpl'); - - ?> - - - -See also [`display()`](#api.display), [`fetch()`](#api.fetch), -[`{include}`](#language.function.include) and -[`{insert}`](#language.function.insert) diff --git a/docs/programmers/api-functions/api-test-install.md b/docs/programmers/api-functions/api-test-install.md index 918bd220..bba64a19 100644 --- a/docs/programmers/api-functions/api-test-install.md +++ b/docs/programmers/api-functions/api-test-install.md @@ -14,7 +14,7 @@ installation can be accessed. It does output a corresponding protocol. <?php - require_once('Smarty.class.php'); + use Smarty\Smarty; $smarty = new Smarty(); $smarty->testInstall(); ?> diff --git a/docs/programmers/api-variables.md b/docs/programmers/api-variables.md deleted file mode 100644 index ee9c0761..00000000 --- a/docs/programmers/api-variables.md +++ /dev/null @@ -1,63 +0,0 @@ -Smarty Class Variables {#api.variables} -====================== - -These are all of the available Smarty class variables. You can access -them directly, or use the corresponding setter/getter methods. - -- [$allow_php_templates](./api-variables/variable-allow-php-templates.md) -- [$auto_literal](./api-variables/variable-auto-literal.md) -- [$autoload_filters](./api-variables/variable-autoload-filters.md) -- [$cache_dir](./api-variables/variable-cache-dir.md) -- [$cache_id](./api-variables/variable-cache-id.md) -- [$cache_lifetime](./api-variables/variable-cache-lifetime.md) -- [$cache_locking](./api-variables/variable-cache-locking.md) -- [$cache_modified_check](./api-variables/variable-cache-modified-check.md) -- [$caching](./api-variables/variable-caching.md) -- [$caching_type](./api-variables/variable-caching-type.md) -- [$compile_check](./api-variables/variable-compile-check.md) -- [$compile_dir](./api-variables/variable-compile-dir.md) -- [$compile_id](./api-variables/variable-compile-id.md) -- [$compile_locking](./api-variables/variable-compile-locking.md) -- [$compiler_class](./api-variables/variable-compiler-class.md) -- [$config_booleanize](./api-variables/variable-config-booleanize.md) -- [$config_dir](./api-variables/variable-config-dir.md) -- [$config_overwrite](./api-variables/variable-config-overwrite.md) -- [$config_read_hidden](./api-variables/variable-config-read-hidden.md) -- [$debug_tpl](./api-variables/variable-debug-template.md) -- [$debugging](./api-variables/variable-debugging.md) -- [$debugging_ctrl](./api-variables/variable-debugging-ctrl.md) -- [$default_config_type](./api-variables/variable-default-config-type.md) -- [$default_modifiers](./api-variables/variable-default-modifiers.md) -- [$default_resource_type](./api-variables/variable-default-resource-type.md) -- [$default_config_handler_func](./api-variables/variable-default-config-handler-func.md) -- [$default_template_handler_func](./api-variables/variable-default-template-handler-func.md) -- [$direct_access_security](./api-variables/variable-direct-access-security.md) -- [$error_reporting](./api-variables/variable-error-reporting.md) -- [$escape_html](./api-variables/variable-escape-html.md) -- [$force_cache](./api-variables/variable-force-cache.md) -- [$force_compile](./api-variables/variable-force-compile.md) -- [$left_delimiter](./api-variables/variable-left-delimiter.md) -- [$locking_timeout](./api-variables/variable-locking-timeout.md) -- [$merge_compiled_includes](./api-variables/variable-merge-compiled-includes.md) -- [$plugins_dir](./api-variables/variable-plugins-dir.md) -- [$right_delimiter](./api-variables/variable-right-delimiter.md) -- [$smarty_debug_id](./api-variables/variable-smarty-debug-id.md) -- [$template_dir](./api-variables/variable-template-dir.md) -- [$trusted_dir](./api-variables/variable-trusted-dir.md) -- [$use_include_path](./api-variables/variable-use-include-path.md) -- [$use_sub_dirs](./api-variables/variable-use-sub-dirs.md) - -> **Note** -> -> All class variables have magic setter/getter methods available. -> setter/getter methods are camelCaseFormat, unlike the variable itself. -> So for example, you can set and get the \$smarty-\>template\_dir -> variable with \$smarty-\>setTemplateDir(\$dir) and \$dir = -> \$smarty-\>getTemplateDir() respectively. - -> **Note** -> -> See -> [`Changing settings by template`](./advanced-features/advanced-features-template-settings.md) -> section for how to change Smarty class variables for individual -> templates. diff --git a/docs/programmers/api-variables/variable-allow-php-templates.md b/docs/programmers/api-variables/variable-allow-php-templates.md deleted file mode 100644 index e15520e2..00000000 --- a/docs/programmers/api-variables/variable-allow-php-templates.md +++ /dev/null @@ -1,18 +0,0 @@ -\$allow\_php\_templates {#variable.allow.php.templates} -======================= - -By default the PHP template file resource is disabled. Setting -`$allow_php_templates` to TRUE will enable PHP template files. - -::: {.informalexample} - - <?php - $smarty->allow_php_templates = true; - ?> - - -::: - -> **Note** -> -> The PHP template file resource is an undocumented deprecated feature. diff --git a/docs/programmers/api-variables/variable-autoload-filters.md b/docs/programmers/api-variables/variable-autoload-filters.md deleted file mode 100644 index 8a300b06..00000000 --- a/docs/programmers/api-variables/variable-autoload-filters.md +++ /dev/null @@ -1,21 +0,0 @@ -\$autoload\_filters {#variable.autoload.filters} -=================== - -If there are some filters that you wish to load on every template -invocation, you can specify them using this variable and Smarty will -automatically load them for you. The variable is an associative array -where keys are filter types and values are arrays of the filter names. -For example: - -::: {.informalexample} - - <?php - $smarty->autoload_filters = array('pre' => array('trim', 'stamp'), - 'output' => array('convert')); - ?> - - -::: - -See also [`registerFilter()`](#api.register.filter) and -[`loadFilter()`](#api.load.filter) diff --git a/docs/programmers/api-variables/variable-cache-lifetime.md b/docs/programmers/api-variables/variable-cache-lifetime.md index c9624b55..481fbee8 100644 --- a/docs/programmers/api-variables/variable-cache-lifetime.md +++ b/docs/programmers/api-variables/variable-cache-lifetime.md @@ -5,8 +5,8 @@ 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 turned on (either - Smarty::CACHING\_LIFETIME\_CURRENT or - Smarty::CACHING\_LIFETIME\_SAVED) for `$cache_lifetime` to have any + \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT or + \Smarty\Smarty::CACHING\_LIFETIME\_SAVED) for `$cache_lifetime` to have any purpose. - A `$cache_lifetime` value of -1 will force the cache to never @@ -14,11 +14,11 @@ Once this time has expired, the cache will be regenerated. - A value of 0 will cause the cache to always regenerate (good for testing only, to disable caching a more efficient method is to set - [`$caching`](#variable.caching) = Smarty::CACHING\_OFF). + [`$caching`](#variable.caching) = \Smarty\Smarty::CACHING\_OFF). - If you want to give certain templates their own cache lifetime, you could do this by setting [`$caching`](#variable.caching) = - Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a + \Smarty\Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a unique value just before calling [`display()`](#api.display) or [`fetch()`](#api.fetch). diff --git a/docs/programmers/api-variables/variable-cache-modified-check.md b/docs/programmers/api-variables/variable-cache-modified-check.md index 05e00bb9..815be255 100644 --- a/docs/programmers/api-variables/variable-cache-modified-check.md +++ b/docs/programmers/api-variables/variable-cache-modified-check.md @@ -4,8 +4,7 @@ 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}`](#language.function.insert) tags. +the content. See also [`$caching`](#variable.caching), [`$cache_lifetime`](#variable.cache.lifetime), and the [caching diff --git a/docs/programmers/api-variables/variable-caching.md b/docs/programmers/api-variables/variable-caching.md index 9377e3b6..7304e41d 100644 --- a/docs/programmers/api-variables/variable-caching.md +++ b/docs/programmers/api-variables/variable-caching.md @@ -3,21 +3,21 @@ This tells Smarty whether or not to cache the output of the templates to the [`$cache_dir`](#variable.cache.dir). By default this is set to the -constant Smarty::CACHING\_OFF. If your templates consistently generate +constant \Smarty\Smarty::CACHING\_OFF. If your templates consistently generate the same content, it is advisable to turn on `$caching`, as this may result in significant performance gains. You can also have [multiple](#caching.multiple.caches) caches for the same template. -- A constant value of Smarty::CACHING\_LIFETIME\_CURRENT or - Smarty::CACHING\_LIFETIME\_SAVED enables caching. +- A constant value of \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT or + \Smarty\Smarty ::CACHING\_LIFETIME\_SAVED enables caching. -- A value of Smarty::CACHING\_LIFETIME\_CURRENT tells Smarty to use +- A value of \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT tells Smarty to use the current [`$cache_lifetime`](#variable.cache.lifetime) variable to determine if the cache has expired. -- A value of Smarty::CACHING\_LIFETIME\_SAVED tells Smarty to use the +- A value of \Smarty\Smarty::CACHING\_LIFETIME\_SAVED tells Smarty to use the [`$cache_lifetime`](#variable.cache.lifetime) value at the time the cache was generated. This way you can set the [`$cache_lifetime`](#variable.cache.lifetime) just before diff --git a/docs/programmers/api-variables/variable-compile-check.md b/docs/programmers/api-variables/variable-compile-check.md deleted file mode 100644 index 075e7f17..00000000 --- a/docs/programmers/api-variables/variable-compile-check.md +++ /dev/null @@ -1,30 +0,0 @@ -\$compile\_check {#variable.compile.check} -================ - -Upon each invocation of the PHP application, Smarty tests to see if the -current template has changed (different timestamp) since the last time -it was compiled. If it has changed, it recompiles that template. If the -template has yet not been compiled at all, it will compile regardless of -this setting. By default this variable is set to TRUE. - -Once an application is put into production (ie the templates won\'t be -changing), the compile check step is no longer needed. Be sure to set -`$compile_check` to FALSE for maximum 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. - -Note that up to Smarty 4.x, Smarty will check for the existence of -the source template even if `$compile_check` is disabled. - -If [`$caching`](#variable.caching) is enabled and `$compile_check` is -enabled, then the cache files will get regenerated if an involved -template file or config file was updated. - -As of Smarty 3.1 `$compile_check` can be set to the value -`Smarty::COMPILECHECK_CACHEMISS`. This enables Smarty to revalidate the -compiled template, once a cache file is regenerated. So if there was a -cached template, but it\'s expired, Smarty will run a single -compile\_check before regenerating the cache. - -See [`$force_compile`](#variable.force.compile) and -[`clearCompiledTemplate()`](#api.clear.compiled.tpl). diff --git a/docs/programmers/api-variables/variable-debug-template.md b/docs/programmers/api-variables/variable-debug-template.md index faec0e17..11a80529 100644 --- a/docs/programmers/api-variables/variable-debug-template.md +++ b/docs/programmers/api-variables/variable-debug-template.md @@ -2,8 +2,7 @@ ============ This is the name of the template file used for the debugging console. By -default, it is named `debug.tpl` and is located in the -[`SMARTY_DIR`](#constant.smarty.dir). +default, it is named `debug.tpl` and is located in `src/debug.tpl`. See also [`$debugging`](#variable.debugging) and the [debugging console](#chapter.debugging.console) section. diff --git a/docs/programmers/api-variables/variable-default-config-handler-func.md b/docs/programmers/api-variables/variable-default-config-handler-func.md index 0d6ec5e0..50eb65bb 100644 --- a/docs/programmers/api-variables/variable-default-config-handler-func.md +++ b/docs/programmers/api-variables/variable-default-config-handler-func.md @@ -8,11 +8,11 @@ resource. > > The default handler is currently only invoked for file resources. It > is not triggered when the resource itself cannot be found, in which -> case a SmartyException is thrown. +> case a \Smarty\Exception is thrown. <?php - + use Smarty\Smarty; $smarty = new Smarty(); $smarty->default_config_handler_func = 'my_default_config_handler_func'; diff --git a/docs/programmers/api-variables/variable-default-template-handler-func.md b/docs/programmers/api-variables/variable-default-template-handler-func.md index d8fcbb1a..96c8190d 100644 --- a/docs/programmers/api-variables/variable-default-template-handler-func.md +++ b/docs/programmers/api-variables/variable-default-template-handler-func.md @@ -8,11 +8,11 @@ resource. > > The default handler is currently only invoked for file resources. It > is not triggered when the resource itself cannot be found, in which -> case a SmartyException is thrown. +> case a \Smarty\Exception is thrown. <?php - + use Smarty\Smarty; $smarty = new Smarty(); $smarty->default_template_handler_func = 'my_default_template_handler_func'; diff --git a/docs/programmers/api-variables/variable-direct-access-security.md b/docs/programmers/api-variables/variable-direct-access-security.md deleted file mode 100644 index f471f5de..00000000 --- a/docs/programmers/api-variables/variable-direct-access-security.md +++ /dev/null @@ -1,13 +0,0 @@ -\$direct\_access\_security {#variable.direct.access.security} -========================== - -Direct access security inhibits direct browser access to compiled or -cached template files. - -Direct access security is enabled by default. To disable it set -`$direct_access_security` to FALSE. - -> **Note** -> -> This is a compile time option. If you change the setting you must make -> sure that the templates get recompiled. diff --git a/docs/programmers/api-variables/variable-error-reporting.md b/docs/programmers/api-variables/variable-error-reporting.md index c0aa9ced..ee28d47a 100644 --- a/docs/programmers/api-variables/variable-error-reporting.md +++ b/docs/programmers/api-variables/variable-error-reporting.md @@ -7,7 +7,7 @@ When this value is set to a non-null-value it\'s value is used as php\'s Smarty 3.1.2 introduced the [`muteExpectedErrors()`](#api.mute.expected.errors) function. Calling -`Smarty::muteExpectedErrors();` after setting up custom error handling +`\Smarty\Smarty::muteExpectedErrors();` after setting up custom error handling will ensure that warnings and notices (deliberately) produced by Smarty will not be passed to other custom error handlers. If your error logs are filling up with warnings regarding `filemtime()` or `unlink()` diff --git a/docs/programmers/api-variables/variable-plugins-dir.md b/docs/programmers/api-variables/variable-plugins-dir.md deleted file mode 100644 index 8a7cfcdb..00000000 --- a/docs/programmers/api-variables/variable-plugins-dir.md +++ /dev/null @@ -1,28 +0,0 @@ -\$plugins\_dir {#variable.plugins.dir} -============== - -This is the directory or directories where Smarty will look for the -plugins that it needs. Default is `plugins/` under the -[`SMARTY_DIR`](#constant.smarty.dir). If you supply a relative path, -Smarty will first look under the [`SMARTY_DIR`](#constant.smarty.dir), -then relative to the current working directory, then relative to the PHP -include\_path. If `$plugins_dir` is an array of directories, Smarty will -search for your plugin in each plugin directory **in the order they are -given**. - -> **Note** -> -> For best performance, do not setup your `$plugins_dir` to have to use -> the PHP include path. Use an absolute pathname, or a path relative to -> `SMARTY_DIR` or the current working directory. - -> **Note** -> -> As of Smarty 3.1 the attribute \$plugins\_dir is no longer accessible -> directly. Use [`getPluginsDir()`](#api.get.plugins.dir), -> [`setPluginsDir()`](#api.set.plugins.dir) and -> [`addPluginsDir()`](#api.add.plugins.dir) instead. - -See also [`getPluginsDir()`](#api.get.plugins.dir), -[`setPluginsDir()`](#api.set.plugins.dir) and -[`addPluginsDir()`](#api.add.plugins.dir). diff --git a/docs/programmers/api-variables/variable-template-dir.md b/docs/programmers/api-variables/variable-template-dir.md index 1db9c413..eb91d2c2 100644 --- a/docs/programmers/api-variables/variable-template-dir.md +++ b/docs/programmers/api-variables/variable-template-dir.md @@ -15,22 +15,12 @@ found. > document root. > **Note** -> -> If the directories known to `$template_dir` are relative to -> directories known to the -> [include\_path](https://www.php.net/ini.core.php#ini.include-path) you -> need to activate the [`$use_include_path`](#variable.use.include.path) -> option. - -> **Note** -> > As of Smarty 3.1 the attribute \$template\_dir is no longer accessible > directly. Use [`getTemplateDir()`](#api.get.template.dir), > [`setTemplateDir()`](#api.set.template.dir) and > [`addTemplateDir()`](#api.add.template.dir) instead. See also [`Template Resources`](#resources), -[`$use_include_path`](#variable.use.include.path), [`getTemplateDir()`](#api.get.template.dir), [`setTemplateDir()`](#api.set.template.dir) and [`addTemplateDir()`](#api.add.template.dir). diff --git a/docs/programmers/api-variables/variable-trusted-dir.md b/docs/programmers/api-variables/variable-trusted-dir.md deleted file mode 100644 index 9720ae8a..00000000 --- a/docs/programmers/api-variables/variable-trusted-dir.md +++ /dev/null @@ -1,8 +0,0 @@ -\$trusted\_dir {#variable.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 -[`{insert}`](#language.function.insert.php). diff --git a/docs/programmers/api-variables/variable-use-include-path.md b/docs/programmers/api-variables/variable-use-include-path.md index 90f55f07..e69de29b 100644 --- a/docs/programmers/api-variables/variable-use-include-path.md +++ b/docs/programmers/api-variables/variable-use-include-path.md @@ -1,49 +0,0 @@ -\$use\_include\_path {#variable.use.include.path} -==================== - -This tells smarty to respect the -[include\_path](https://www.php.net/ini.core.php#ini.include-path) within -the [`File Template Resource`](#resources.file) handler and the plugin -loader to resolve the directories known to -[`$template_dir`](#variable.template.dir). The flag also makes the -plugin loader check the include\_path for -[`$plugins_dir`](#variable.plugins.dir). - -> **Note** -> -> You should not design your applications to rely on the include\_path, -> as this may - depending on your implementation - slow down your system -> (and Smarty) considerably. - -If use\_include\_path is enabled, file discovery for -[`$template_dir`](#variable.template.dir) and -[`$plugins_dir`](#variable.plugins.dir) work as follows. - -- For each element `$directory` in array (\$template\_dir or - \$plugins\_dir) do - -- Test if requested file is in `$directory` relative to the [current - working directory](https://www.php.net/function.getcwd.php). If file - found, return it. - -- For each `$path` in include\_path do - -- Test if requested file is in `$directory` relative to the `$path` - (possibly relative to the [current working - directory](https://www.php.net/function.getcwd.php)). If file found, - return it. - -- Try default\_handler or fail. - -This means that whenever a directory/file relative to the current -working directory is encountered, it is preferred over anything -potentially accessible through the include\_path. - -> **Note** -> -> Smarty does not filter elements of the include\_path. That means a -> \".:\" within your include path will trigger the current working -> directory lookup twice. - -See also [`Template Resources`](#resources) and -[`$template_dir`](#variable.template.dir) diff --git a/docs/programmers/caching.md b/docs/programmers/caching.md deleted file mode 100644 index 5656b71b..00000000 --- a/docs/programmers/caching.md +++ /dev/null @@ -1,24 +0,0 @@ -Caching -======= - -Caching is used to speed up a call to [`display()`](./api-functions/api-display.md) or -[`fetch()`](./api-functions/api-fetch.md) by saving its output to a file. If a cached -version of the call is available, that is displayed instead of -regenerating the output. Caching can speed things up tremendously, -especially templates with longer computation times. Since the output of -[`display()`](./api-functions/api-display.md) or [`fetch()`](./api-functions/api-fetch.md) is cached, one -cache file could conceivably be made up of several template files, -config files, etc. - -Since templates are dynamic, it is important to be careful what you are -caching and for how long. For instance, if you are displaying the front -page of your website that does not change its content very often, it -might work well to cache this page for an hour or more. On the other -hand, if you are displaying a page with a timetable containing new -information by the minute, it would not make sense to cache this page. - -## Table of contents -- [Setting Up Caching](./caching/caching-setting-up.md) -- [Multiple Caches Per Page](./caching/caching-multiple-caches.md) -- [Controlling Cacheability of Output](./caching/caching-groups.md) -- [Custom Cache Implementation](./caching/caching-custom.md) diff --git a/docs/programmers/caching/caching-cacheable.md b/docs/programmers/caching/caching-cacheable.md deleted file mode 100644 index ee9b6009..00000000 --- a/docs/programmers/caching/caching-cacheable.md +++ /dev/null @@ -1,176 +0,0 @@ -Controlling Cacheability of Output {#caching.cacheable} -================================== - -If caching is enabled normally the whole final output of the page gets -cached. However Smarty3 offers several options how to exclude sections -of your output from caching. - -> **Note** -> -> Be sure any variables used within a non-cached section are also -> assigned from PHP when the page is loaded from the cache. - -Cacheability of Template Section {#cacheability.sections} --------------------------------- - -A larger section of your template can easily excluded from caching by -using the [`{nocache}`](#language.function.nocache) and -[`{/nocache}`](#language.function.nocache) tags. - - - - Today's date is - {nocache} - {$smarty.now|date_format} - {/nocache} - - - -The above code will output the current date on a cached page. - -Cacheability of Tags {#cacheability.tags} --------------------- - -Caching for an individual tag can be disabled by adding the \"nocache\" -option flag to the tag. - - - Today's date is - {$smarty.now|date_format nocache} - - - -Cacheability of Variables {#cacheability.variables} -------------------------- - -You can [`assign()`](#api.assign) variables as not cachable. Any tag -which uses such variable will be automatically executed in nocache mode. - -> **Note** -> -> If a tag is executed in nocache mode you must make sure that all other -> variables used by that tag are also assigned from PHP when the page is -> loaded from the cache. - -> **Note** -> -> The nocache status of an assigned variable will effect the compiled -> template code. If you change the status you must manually delete -> existing compiled and cached template files to force a recompile. - - - // assign $foo as nocahe variable - $smarty->assign('foo',time(),true); - - - Dynamic time value is {$foo} - - - -Cacheability of Plugins {#cacheability.plugins} ------------------------ - -The cacheability of plugins can be declared when registering them. The -third parameter to [`registerPlugin()`](#api.register.plugin) is called -`$cacheable` and defaults to TRUE. - -When registering a plugin with `$cacheable=false` the plugin is called -everytime the page is displayed, even if the page comes from the cache. -The plugin function behaves a little like an -[`{insert}`](#plugins.inserts) function. - -> **Note** -> -> The `$cacheable` status will effect the compiled template code. If you -> change the status you must manually delete existing compiled and -> cached template files to force a recompile. - -In contrast to [`{insert}`](#plugins.inserts) the attributes to the -plugins are not cached by default. They can be declared to be cached -with the fourth parameter `$cache_attrs`. `$cache_attrs` is an array of -attribute-names that should be cached, so the plugin-function get value -as it was the time the page was written to cache everytime it is fetched -from the cache. - - - <?php - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - function remaining_seconds($params, $smarty) { - $remain = $params['endtime'] - time(); - if($remain >= 0){ - return $remain . ' second(s)'; - }else{ - return 'done'; - } - } - - $smarty->registerPlugin('function','remaining', 'remaining_seconds', false, array('endtime')); - - if (!$smarty->isCached('index.tpl')) { - // fetch $obj from db and assign... - $smarty->assignByRef('obj', $obj); - } - - $smarty->display('index.tpl'); - ?> - - - -where `index.tpl` is: - - - Time Remaining: {remaining endtime=$obj->endtime} - - - -The number of seconds till the endtime of `$obj` is reached changes on -each display of the page, even if the page is cached. Since the endtime -attribute is cached the object only has to be pulled from the database -when page is written to the cache but not on subsequent requests of the -page. - - - index.php: - - <?php - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - function smarty_block_dynamic($param, $content, $smarty) { - return $content; - } - $smarty->registerPlugin('block','dynamic', 'smarty_block_dynamic', false); - - $smarty->display('index.tpl'); - ?> - - - -where `index.tpl` is: - - - Page created: {'0'|date_format:'%D %H:%M:%S'} - - {dynamic} - - Now is: {'0'|date_format:'%D %H:%M:%S'} - - ... do other stuff ... - - {/dynamic} - - - -When reloading the page you will notice that both dates differ. One is -"dynamic" one is "static". You can do everything between -`{dynamic}...{/dynamic}` and be sure it will not be cached like the rest -of the page. - -> **Note** -> -> The above example shall just demonstrate how a dynamic block plugins -> works. See -> [`Cacheability of Template Section`](#cacheability.sections) on how to -> disable caching of a template section by the built-in -> [`{nocache}`](#language.function.nocache) and -> [`{/nocache}`](#language.function.nocache) tags. diff --git a/docs/programmers/caching/caching-custom.md b/docs/programmers/caching/caching-custom.md deleted file mode 100644 index 77d2ce7b..00000000 --- a/docs/programmers/caching/caching-custom.md +++ /dev/null @@ -1,296 +0,0 @@ -Custom Cache Implementation {#caching.custom} -=========================== - -As an alternative to using the default file-based caching mechanism, you -can specify a custom cache implementation that will be used to read, -write and clear cached files. - -> **Note** -> -> In Smarty2 this used to be a callback function called -> `$cache_handler_func`. Smarty3 replaced this callback by the -> `Smarty_CacheResource` module. - -With a custom cache implementation you\'re likely trying to achieve at -least one of the following goals: replace the slow filesystem by a -faster storage engine, centralize the cache to be accessible to multiple -servers. - -Smarty allows CacheResource implementations to use one of the APIs -`Smarty_CacheResource_Custom` or `Smarty_CacheResource_KeyValueStore`. -`Smarty_CacheResource_Custom` is a simple API directing all read, write, -clear calls to your implementation. This API allows you to store -wherever and however you deem fit. The -`Smarty_CacheResource_KeyValueStore` API allows you to turn any \"dumb\" -KeyValue-Store (like APC, Memcache, ...) into a full-featured -CacheResource implementation. That is, everything around deep -cache-groups like \"a\|b\|c\" is being handled for you in way that -allows clearing the cache-group \"a\" and all nested groups are cleared -as well - even though KeyValue-Stores don\'t allow this kind of -hierarchy by nature. - -Custom CacheResources may be put in a file `cacheresource.foobarxyz.php` -within your [`$plugins_dir`](#variable.plugins.dir), or registered on -runtime with [`registerCacheResource()`](#api.register.cacheresource). -In either case you need to set [`$caching_type`](#variable.caching.type) -to invoke your custom CacheResource implementation. - - - <?php - - require_once 'libs/Smarty.class.php'; - $smarty = new Smarty(); - $smarty->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: - * <pre>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;</pre> - * - * @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; - } - - /** - * Save content to cache - * - * @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 integer|null $exp_time seconds till expiration time in seconds or null - * @param string $content content to cache - * @return boolean success - */ - protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content) - { - $this->save->execute(array( - 'id' => $id, - 'name' => $name, - 'cache_id' => $cache_id, - 'compile_id' => $compile_id, - 'content' => $content, - )); - return !!$this->save->rowCount(); - } - - /** - * Delete content from cache - * - * @param string $name template name - * @param string $cache_id cache id - * @param string $compile_id compile id - * @param integer|null $exp_time seconds till expiration or null - * @return integer number of deleted caches - */ - protected function delete($name, $cache_id, $compile_id, $exp_time) - { - // delete the whole cache - if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) { - // returning the number of deleted caches would require a second query to count them - $query = $this->db->query('TRUNCATE TABLE output_cache'); - return -1; - } - // build the filter - $where = array(); - // equal test name - if ($name !== null) { - $where[] = 'name = ' . $this->db->quote($name); - } - // equal test compile_id - if ($compile_id !== null) { - $where[] = 'compile_id = ' . $this->db->quote($compile_id); - } - // range test expiration time - if ($exp_time !== null) { - $where[] = 'modified < DATE_SUB(NOW(), INTERVAL ' . intval($exp_time) . ' SECOND)'; - } - // equal test cache_id and match sub-groups - if ($cache_id !== null) { - $where[] = '(cache_id = '. $this->db->quote($cache_id) - . ' OR cache_id LIKE '. $this->db->quote($cache_id .'|%') .')'; - } - // run delete query - $query = $this->db->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where)); - return $query->rowCount(); - } - } - - - - - <?php - - require_once 'libs/Smarty.class.php'; - $smarty = new Smarty(); - $smarty->caching_type = 'memcache'; - - /** - * Memcache CacheResource - * - * CacheResource Implementation based on the KeyValueStore API to use - * memcache as the storage resource for Smarty's output caching. - * - * Note that memcache has a limitation of 256 characters per cache-key. - * To avoid complications all cache-keys are translated to a sha1 hash. - * - * @package CacheResource-examples - * @author Rodney Rehm - */ - class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore { - /** - * memcache instance - * @var Memcache - */ - protected $memcache = null; - - public function __construct() - { - $this->memcache = new Memcache(); - $this->memcache->addServer( '127.0.0.1', 11211 ); - } - - /** - * Read values for a set of keys from cache - * - * @param array $keys list of keys to fetch - * @return array list of values with the given keys used as indexes - * @return boolean true on success, false on failure - */ - protected function read(array $keys) - { - $_keys = $lookup = array(); - foreach ($keys as $k) { - $_k = sha1($k); - $_keys[] = $_k; - $lookup[$_k] = $k; - } - $_res = array(); - $res = $this->memcache->get($_keys); - foreach ($res as $k => $v) { - $_res[$lookup[$k]] = $v; - } - return $_res; - } - - /** - * Save values for a set of keys to cache - * - * @param array $keys list of values to save - * @param int $expire expiration time - * @return boolean true on success, false on failure - */ - protected function write(array $keys, $expire=null) - { - foreach ($keys as $k => $v) { - $k = sha1($k); - $this->memcache->set($k, $v, 0, $expire); - } - return true; - } - - /** - * Remove values from cache - * - * @param array $keys list of keys to delete - * @return boolean true on success, false on failure - */ - protected function delete(array $keys) - { - foreach ($keys as $k) { - $k = sha1($k); - $this->memcache->delete($k); - } - return true; - } - - /** - * Remove *all* values from cache - * - * @return boolean true on success, false on failure - */ - protected function purge() - { - return $this->memcache->flush(); - } - } - - - diff --git a/docs/programmers/caching/caching-groups.md b/docs/programmers/caching/caching-groups.md deleted file mode 100644 index 7e248b2f..00000000 --- a/docs/programmers/caching/caching-groups.md +++ /dev/null @@ -1,60 +0,0 @@ -Cache Groups {#caching.groups} -============ - -You can do more elaborate grouping by setting up `$cache_id` groups. -This is accomplished by separating each sub-group with a vertical bar -`|` in the `$cache_id` value. You can have as many sub-groups as you -like. - -- You can think of cache groups like a directory hierarchy. For - instance, a cache group of `'a|b|c'` could be thought of as the - directory structure `'/a/b/c/'`. - -- `clearCache(null,'a|b|c')` would be like removing the files - `'/a/b/c/*'`. `clearCache(null,'a|b')` would be like removing the - files `'/a/b/*'`. - -- If you specify a [`$compile_id`](#variable.compile.id) such as - `clearCache(null,'a|b','foo')` it is treated as an appended cache - group `'/a/b/c/foo/'`. - -- If you specify a template name such as - `clearCache('foo.tpl','a|b|c')` then Smarty will attempt to remove - `'/a/b/c/foo.tpl'`. - -- You CANNOT remove a specified template name under multiple cache - groups such as `'/a/b/*/foo.tpl'`, the cache grouping works - left-to-right ONLY. You will need to group your templates under a - single cache group hierarchy to be able to clear them as a group. - -Cache grouping should not be confused with your template directory -hierarchy, the cache grouping has no knowledge of how your templates are -structured. So for example, if you have a template structure like -`themes/blue/index.tpl` and you want to be able to clear all the cache -files for the "blue" theme, you will need to create a cache group -structure that mimics your template file structure, such as -`display('themes/blue/index.tpl','themes|blue')`, then clear them with -`clearCache(null,'themes|blue')`. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - // clear all caches with 'sports|basketball' as the first two cache_id groups - $smarty->clearCache(null,'sports|basketball'); - - // clear all caches with "sports" as the first cache_id group. This would - // include "sports|basketball", or "sports|(anything)|(anything)|(anything)|..." - $smarty->clearCache(null,'sports'); - - // clear the foo.tpl cache file with "sports|basketball" as the cache_id - $smarty->clearCache('foo.tpl','sports|basketball'); - - - $smarty->display('index.tpl','sports|basketball'); - ?> - - diff --git a/docs/programmers/caching/caching-multiple-caches.md b/docs/programmers/caching/caching-multiple-caches.md deleted file mode 100644 index 40fffc3d..00000000 --- a/docs/programmers/caching/caching-multiple-caches.md +++ /dev/null @@ -1,87 +0,0 @@ -Multiple Caches Per Page {#caching.multiple.caches} -======================== - -You can have multiple cache files for a single call to -[`display()`](#api.display) or [`fetch()`](#api.fetch). Let\'s say that -a call to `display('index.tpl')` may have several different output -contents depending on some condition, and you want separate caches for -each one. You can do this by passing a `$cache_id` as the second -parameter to the function call. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - $my_cache_id = $_GET['article_id']; - - $smarty->display('index.tpl', $my_cache_id); - ?> - - - -Above, we are passing the variable `$my_cache_id` to -[`display()`](#api.display) as the `$cache_id`. For each unique value of -`$my_cache_id`, a separate cache will be generated for `index.tpl`. In -this example, `article_id` was passed in the URL and is used as the -`$cache_id`. - -> **Note** -> -> Be very cautious when passing values from a client (web browser) into -> Smarty or any PHP application. Although the above example of using the -> article\_id from the URL looks handy, it could have bad consequences. -> The `$cache_id` is used to create a directory on the file system, so -> if the user decided to pass an extremely large value for article\_id, -> or write a script that sends random article\_id\'s at a rapid pace, -> this could possibly cause problems at the server level. Be sure to -> sanitize any data passed in before using it. In this instance, maybe -> you know the article\_id has a length of ten characters and is made up -> of alpha-numerics only, and must be a valid article\_id in the -> database. Check for this! - -Be sure to pass the same `$cache_id` as the second parameter to -[`isCached()`](#api.is.cached) and [`clearCache()`](#api.clear.cache). - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - $my_cache_id = $_GET['article_id']; - - if(!$smarty->isCached('index.tpl',$my_cache_id)) { - // No cache available, do variable assignments here. - $contents = get_database_contents(); - $smarty->assign($contents); - } - - $smarty->display('index.tpl',$my_cache_id); - ?> - - - -You can clear all caches for a particular `$cache_id` by passing NULL as -the first parameter to [`clearCache()`](#api.clear.cache). - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - // clear all caches with "sports" as the $cache_id - $smarty->clearCache(null,'sports'); - - $smarty->display('index.tpl','sports'); - ?> - - - -In this manner, you can "group" your caches together by giving them the -same `$cache_id`. diff --git a/docs/programmers/caching/caching-setting-up.md b/docs/programmers/caching/caching-setting-up.md deleted file mode 100644 index bc9d2ad9..00000000 --- a/docs/programmers/caching/caching-setting-up.md +++ /dev/null @@ -1,153 +0,0 @@ -Setting Up Caching {#caching.setting.up} -================== - -The first thing to do is enable caching by setting -[`$caching`](#variable.caching) to one of -`Smarty::CACHING_LIFETIME_CURRENT` or `Smarty::CACHING_LIFETIME_SAVED`. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - // uses the value of $smarty->cacheLifetime() to determine - // the number of seconds a cache is good for - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - $smarty->display('index.tpl'); - ?> - - - -With caching enabled, the function call to `display('index.tpl')` will -render the template as usual, but also saves a copy of its output to a -file (a cached copy) in the [`$cache_dir`](#variable.cache.dir). On the -next call to `display('index.tpl')`, the cached copy will be used -instead of rendering the template again. - -> **Note** -> -> The files in the [`$cache_dir`](#variable.cache.dir) are named similar -> to the template name. Although they end in the `.php` extension, they -> are not intended to be directly executable. Do not edit these files! - -Each cached page has a limited lifetime determined by -[`$cache_lifetime`](#variable.cache.lifetime). The default value is 3600 -seconds, or one hour. After that time expires, the cache is regenerated. -It is possible to give individual caches their own expiration time by -setting [`$caching`](#variable.caching) to -`Smarty::CACHING_LIFETIME_SAVED`. See -[`$cache_lifetime`](#variable.cache.lifetime) for more details. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - // retain current cache lifetime for each specific display call - $smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED); - - // set the cache_lifetime for index.tpl to 5 minutes - $smarty->setCacheLifetime(300); - $smarty->display('index.tpl'); - - // set the cache_lifetime for home.tpl to 1 hour - $smarty->setCacheLifetime(3600); - $smarty->display('home.tpl'); - - // NOTE: the following $cache_lifetime setting will not work when $caching - // is set to Smarty::CACHING_LIFETIME_SAVED. - // The cache lifetime for home.tpl has already been set - // to 1 hour, and will no longer respect the value of $cache_lifetime. - // The home.tpl cache will still expire after 1 hour. - $smarty->setCacheLifetime(30); // 30 seconds - $smarty->display('home.tpl'); - ?> - - - -If [`$compile_check`](#variable.compile.check) is enabled (default), -every template file and config file that is involved with the cache file -is checked for modification. If any of the files have been modified -since the cache was generated, the cache is immediately regenerated. -This is a computational overhead, so for optimum performance set -[`$compile_check`](#variable.compile.check) to FALSE. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - $smarty->setCompileCheck(false); - - $smarty->display('index.tpl'); - ?> - - - -If [`$force_compile`](#variable.force.compile) is enabled, the cache -files will always be regenerated. This effectively disables caching, -however this also seriously degrades performance. -[`$force_compile`](#variable.force.compile) is meant to be used for -[debugging](#chapter.debugging.console) purposes. The appropriate way to -disable caching is to set [`$caching`](#variable.caching) to -Smarty::CACHING\_OFF. - -The [`isCached()`](#api.is.cached) function can be used to test if a -template has a valid cache or not. If you have a cached template that -requires something like a database fetch, you can use this to skip that -process. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - if(!$smarty->isCached('index.tpl')) { - // No cache available, do variable assignments here. - $contents = get_database_contents(); - $smarty->assign($contents); - } - - $smarty->display('index.tpl'); - ?> - - - -You can keep parts of a page dynamic (disable caching) with the -[`{nocache}{/nocache}`](#language.function.nocache) block function, the -[`{insert}`](#language.function.insert) function, or by using the -`nocache` parameter for most template functions. - -Let\'s say the whole page can be cached except for a banner that is -displayed down the side of the page. By using the -[`{insert}`](#language.function.insert) function for the banner, you can -keep this element dynamic within the cached content. See the -documentation on [`{insert}`](#language.function.insert) for more -details and examples. - -You can clear all the cache files with the -[`clearAllCache()`](#api.clear.all.cache) function, or individual cache -files [and groups](#caching.groups) with the -[`clearCache()`](#api.clear.cache) function. - - - <?php - require('Smarty.class.php'); - $smarty = new Smarty; - - $smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT); - - // clear only cache for index.tpl - $smarty->clearCache('index.tpl'); - - // clear out all cache files - $smarty->clearAllCache(); - - $smarty->display('index.tpl'); - ?> - - diff --git a/docs/programmers/charset.md b/docs/programmers/charset.md deleted file mode 100644 index 9dedf4dc..00000000 --- a/docs/programmers/charset.md +++ /dev/null @@ -1,44 +0,0 @@ -Charset Encoding {#charset} -================ - -Charset Encoding {#charset.encoding} -================ - -There are a variety of encodings for textual data, ISO-8859-1 (Latin1) -and UTF-8 being the most popular. Unless you change `Smarty::$_CHARSET`, -Smarty recognizes `UTF-8` as the internal charset if -[Multibyte String](https://www.php.net/mbstring) is available, -`ISO-8859-1` if not. - -> **Note** -> -> `ISO-8859-1` has been PHP\'s default internal charset since the -> beginning. Unicode has been evolving since 1991. Since then it has -> become the one charset to conquer them all, as it is capable of -> encoding most of the known characters even across different character -> systems (latin, cyrillic, japanese, ...). `UTF-8` is unicode\'s most -> used encoding, as it allows referencing the thousands of character -> with the smallest size overhead possible. -> -> Since unicode and UTF-8 are very wide spread nowadays, their use is -> strongly encouraged. - -> **Note** -> -> Smarty\'s internals and core plugins are truly UTF-8 compatible since -> Smarty 3.1. To achieve unicode compatibility, the [Multibyte -> String](https://www.php.net/mbstring) PECL is required. Unless your PHP -> environment offers this package, Smarty will not be able to offer -> full-scale UTF-8 compatibility. - - - // use japanese character encoding - if (function_exists('mb_internal_charset')) { - mb_internal_charset('EUC-JP'); - } - - require_once 'libs/Smarty.class.php'; - Smarty::$_CHARSET = 'EUC-JP'; - $smarty = new Smarty(); - - diff --git a/docs/programmers/plugins.md b/docs/programmers/plugins.md deleted file mode 100644 index 41a7ea0c..00000000 --- a/docs/programmers/plugins.md +++ /dev/null @@ -1,44 +0,0 @@ -Extending Smarty With Plugins {#plugins} -============================= - -## Table of contents - -- [How Plugins Work](./plugins/plugins-howto.md) -- [Naming Conventions](./plugins/plugins-naming-conventions.md) -- [Writing Plugins](./plugins/plugins-writing.md) -- [Template Functions](./plugins/plugins-functions.md) -- [Modifiers](./plugins/plugins-modifiers.md) -- [Block Functions](./plugins/plugins-block-functions.md) -- [Compiler Functions](./plugins/plugins-compiler-functions.md) -- [Prefilters/Postfilters](./plugins/plugins-prefilters-postfilters.md) -- [Output Filters](./plugins/plugins-outputfilters.md) -- [Resources](./plugins/plugins-resources.md) -- [Inserts](./plugins/plugins-inserts.md) - -Version 2.0 introduced the plugin architecture that is used for almost -all the customizable functionality of Smarty. This includes: - -- functions - -- modifiers - -- block functions - -- compiler functions - -- prefilters - -- postfilters - -- outputfilters - -- 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. diff --git a/docs/programmers/plugins/plugins-block-functions.md b/docs/programmers/plugins/plugins-block-functions.md deleted file mode 100644 index 0e11c078..00000000 --- a/docs/programmers/plugins/plugins-block-functions.md +++ /dev/null @@ -1,95 +0,0 @@ -Block Functions {#plugins.block.functions} -=============== - -void - -smarty\_block\_ - -name - -array - -\$params - -mixed - -\$content - -object - -\$template - -boolean - -&\$repeat - -Block functions are functions of the form: `{func} .. {/func}`. In other -words, they enclose a template block and operate on the contents of this -block. Block functions take precedence over [custom -functions](#language.custom.functions) of the same name, that is, you -cannot have both custom function `{func}` and block function -`{func}..{/func}`. - -- By default your function implementation is called twice by Smarty: - once for the opening tag, and once for the closing tag. (See - `$repeat` below on how to change this.) - -- Starting with Smarty 3.1 the returned value of the opening tag call - is displayed as well. - -- Only the opening tag of the block function may have - [attributes](#language.syntax.attributes). All attributes passed to - template functions from the template are contained in the `$params` - variable as an associative array. The opening tag attributes are - also accessible to your function when processing the closing tag. - -- The value of the `$content` variable depends on whether your - function is called for the opening or closing tag. In case of the - opening tag, it will be NULL, and in case of the closing tag it will - be the contents of the template block. Note that the template block - will have already been processed by Smarty, so all you will receive - is the template output, not the template source. - -- The parameter `$repeat` is passed by reference to the function - implementation and provides a possibility for it to control how many - times the block is displayed. By default `$repeat` is TRUE at the - first call of the block-function (the opening tag) and FALSE on all - subsequent calls to the block function (the block\'s closing tag). - Each time the function implementation returns with `$repeat` being - TRUE, the contents between `{func}...{/func}` are evaluated and the - function implementation is called again with the new block contents - in the parameter `$content`. - -If you have nested block functions, it\'s possible to find out what the -parent block function is by accessing `$smarty->_tag_stack` variable. -Just do a [`var_dump()`](https://www.php.net/var_dump) on it and the -structure should be apparent. - - - <?php - /* - * Smarty plugin - * ------------------------------------------------------------- - * File: block.translate.php - * Type: block - * Name: translate - * Purpose: translate a block of text - * ------------------------------------------------------------- - */ - function smarty_block_translate($params, $content, Smarty_Internal_Template $template, &$repeat) - { - // only output on the closing tag - if(!$repeat){ - if (isset($content)) { - $lang = $params['lang']; - // do some intelligent translation thing here with $content - return $translation; - } - } - } - ?> - - - -See also: [`registerPlugin()`](#api.register.plugin), -[`unregisterPlugin()`](#api.unregister.plugin). diff --git a/docs/programmers/plugins/plugins-compiler-functions.md b/docs/programmers/plugins/plugins-compiler-functions.md deleted file mode 100644 index ef2454e8..00000000 --- a/docs/programmers/plugins/plugins-compiler-functions.md +++ /dev/null @@ -1,66 +0,0 @@ -Compiler Functions {#plugins.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](#language.custom.functions) registered under the same name, -the compiler function has precedence. - -mixed - -smarty\_compiler\_ - -name - -array - -\$params - -object - -\$smarty - -The compiler function is passed two parameters: the params array which -contains precompiled strings for the attribute values and the Smarty -object. It\'s supposed to return the code to be injected into the -compiled template including the surrounding PHP tags. - - - <?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($params, Smarty $smarty) - { - return "<?php\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>"; - } - ?> - -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'; - ?> - - - -See also [`registerPlugin()`](#api.register.plugin), -[`unregisterPlugin()`](#api.unregister.plugin). diff --git a/docs/programmers/plugins/plugins-functions.md b/docs/programmers/plugins/plugins-functions.md deleted file mode 100644 index 067b9382..00000000 --- a/docs/programmers/plugins/plugins-functions.md +++ /dev/null @@ -1,94 +0,0 @@ -Template Functions {#plugins.functions} -================== - -void - -smarty\_function\_ - -name - -array - -\$params - -object - -\$template - -All [attributes](#language.syntax.attributes) passed to template -functions from the template are contained in the `$params` as an -associative array. - -The output (return value) of the function will be substituted in place -of the function tag in the template, eg the -[`{fetch}`](#language.function.fetch) function. Alternatively, the -function can simply perform some other task without any output, eg the -[`{assign}`](#language.function.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 -`$template` object to do so eg `$template->foo()`. - - - <?php - /* - * Smarty plugin - * ------------------------------------------------------------- - * File: function.eightball.php - * Type: function - * Name: eightball - * Purpose: outputs a random magic answer - * ------------------------------------------------------------- - */ - function smarty_function_eightball($params, Smarty_Internal_Template $template) - { - $answers = array('Yes', - 'No', - 'No way', - 'Outlook not so good', - 'Ask again soon', - 'Maybe in your reality'); - - $result = array_rand($answers); - return $answers[$result]; - } - ?> - -which can be used in the template as: - - Question: Will we ever have time travel? - Answer: {eightball}. - - - - <?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_Internal_Template $template) - { - if (empty($params['var'])) { - trigger_error("assign: missing 'var' parameter"); - return; - } - - if (!in_array('value', array_keys($params))) { - trigger_error("assign: missing 'value' parameter"); - return; - } - - $template->assign($params['var'], $params['value']); - - } - ?> - - - -See also: [`registerPlugin()`](#api.register.plugin), -[`unregisterPlugin()`](#api.unregister.plugin). diff --git a/docs/programmers/plugins/plugins-howto.md b/docs/programmers/plugins/plugins-howto.md deleted file mode 100644 index 5738c3fc..00000000 --- a/docs/programmers/plugins/plugins-howto.md +++ /dev/null @@ -1,18 +0,0 @@ -How Plugins Work {#plugins.howto} -================ - -Plugins are always loaded on demand. Only the specific modifiers, -functions, resources, etc invoked in the templates 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/postfilters and output filters are a bit of a special case. Since -they are not mentioned in the templates, they must be registered or -loaded explicitly via API functions before the template is processed. -The order in which multiple filters of the same type are executed -depends on the order in which they are registered or loaded. - -The [plugins directory](#variable.plugins.dir) can be a string -containing a path or an array containing multiple paths. To install a -plugin, simply place it in one of the directories and Smarty will use it -automatically. diff --git a/docs/programmers/plugins/plugins-inserts.md b/docs/programmers/plugins/plugins-inserts.md deleted file mode 100644 index 370a97bd..00000000 --- a/docs/programmers/plugins/plugins-inserts.md +++ /dev/null @@ -1,48 +0,0 @@ -Inserts {#plugins.inserts} -======= - -Insert plugins are used to implement functions that are invoked by -[`{insert}`](#language.function.insert) tags in the template. - -string - -smarty\_insert\_ - -name - -array - -\$params - -object - -\$template - -The first parameter to the function is an associative array of -attributes passed to the insert. - -The insert function is supposed to return the result which will be -substituted in place of the `{insert}` tag in the template. - - - <?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_Internal_Template $template) - { - if (empty($params['format'])) { - trigger_error("insert time: missing 'format' parameter"); - return; - } - return strftime($params['format']); - } - ?> - - diff --git a/docs/programmers/plugins/plugins-modifiers.md b/docs/programmers/plugins/plugins-modifiers.md deleted file mode 100644 index a4e99daa..00000000 --- a/docs/programmers/plugins/plugins-modifiers.md +++ /dev/null @@ -1,86 +0,0 @@ -Modifiers {#plugins.modifiers} -========= - -[Modifiers](#language.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 to operate. The rest of the parameters are optional, -depending on what kind of operation is to be performed. - -The modifier has to [return](https://www.php.net/return) the result of its -processing. - -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); - } - ?> - - - <?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; - } - ?> - - - -See also [`registerPlugin()`](#api.register.plugin), -[`unregisterPlugin()`](#api.unregister.plugin). diff --git a/docs/programmers/plugins/plugins-naming-conventions.md b/docs/programmers/plugins/plugins-naming-conventions.md deleted file mode 100644 index 15bc2601..00000000 --- a/docs/programmers/plugins/plugins-naming-conventions.md +++ /dev/null @@ -1,51 +0,0 @@ -Naming Conventions {#plugins.naming.conventions} -================== - -Plugin files and functions must follow a very specific naming convention -in order to be located by Smarty. - -**plugin files** must be named as follows: - -> ` -> type.name.php -> ` - -- Where `type` is one of these plugin types: - - - function - - - modifier - - - block - - - compiler - - - prefilter - - - postfilter - - - outputfilter - - - resource - - - insert - -- And `name` should be a valid identifier; letters, numbers, and - underscores only, see [php - variables](https://www.php.net/language.variables). - -- Some examples: `function.html_select_date.php`, `resource.db.php`, - `modifier.spacify.php`. - -**plugin functions** inside the PHP files must be named as follows: - -> `smarty_type_name` - -- The meanings of `type` and `name` are the same as above. - -- An example modifier name `foo` would be - `function smarty_modifier_foo()`. - -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. diff --git a/docs/programmers/plugins/plugins-outputfilters.md b/docs/programmers/plugins/plugins-outputfilters.md deleted file mode 100644 index 4e34ab7e..00000000 --- a/docs/programmers/plugins/plugins-outputfilters.md +++ /dev/null @@ -1,48 +0,0 @@ -Output Filters {#plugins.outputfilters} -============== - -Output filter plugins operate on a template\'s output, after the -template is loaded and executed, but before the output is displayed. - -string - -smarty\_outputfilter\_ - -name - -string - -\$template\_output - -object - -\$template - -The first parameter to the output filter function is the template output -that needs to be processed, and the second parameter is the instance of -Smarty invoking the plugin. The plugin is supposed to do the processing -and return the results. - - - <?php - /* - * Smarty plugin - * ------------------------------------------------------------- - * File: outputfilter.protect_email.php - * Type: outputfilter - * Name: protect_email - * Purpose: Converts @ sign in email addresses to %40 as - * a simple protection against spambots - * ------------------------------------------------------------- - */ - function smarty_outputfilter_protect_email($output, Smarty_Internal_Template $template) - { - return preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!', - '$1%40$2', $output); - } - ?> - - - -See also [`registerFilter()`](#api.register.filter), -[`unregisterFilter()`](#api.unregister.filter). diff --git a/docs/programmers/plugins/plugins-prefilters-postfilters.md b/docs/programmers/plugins/plugins-prefilters-postfilters.md deleted file mode 100644 index 39467cbc..00000000 --- a/docs/programmers/plugins/plugins-prefilters-postfilters.md +++ /dev/null @@ -1,89 +0,0 @@ -Prefilters/Postfilters {#plugins.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 - -\$template - -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 - -\$template - -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. - - - <?php - /* - * Smarty plugin - * ------------------------------------------------------------- - * File: prefilter.pre01.php - * Type: prefilter - * Name: pre01 - * Purpose: Convert html tags to be lowercase. - * ------------------------------------------------------------- - */ - function smarty_prefilter_pre01($source, Smarty_Internal_Template $template) - { - return preg_replace('!<(\w+)[^>]+>!e', 'strtolower("$1")', $source); - } - ?> - - - - - <?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_Internal_Template $template) - { - $compiled = "<pre>\n<?php print_r(\$template->getTemplateVars()); ?>\n</pre>" . $compiled; - return $compiled; - } - ?> - - - -See also [`registerFilter()`](#api.register.filter) and -[`unregisterFilter()`](#api.unregister.filter). diff --git a/docs/programmers/plugins/plugins-resources.md b/docs/programmers/plugins/plugins-resources.md deleted file mode 100644 index 1b1fdf0a..00000000 --- a/docs/programmers/plugins/plugins-resources.md +++ /dev/null @@ -1,128 +0,0 @@ -Resources {#plugins.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. - -Custom Resources may be put in a file `resource.foobarxyz.php` within -your [`$plugins_dir`](#variable.plugins.dir), or registered on runtime -with [`registerResource()`](#api.register.resource). In either case you -will be able to access that resource by prepending its name to the -template you\'re addressing: `foobarxyz:yourtemplate.tpl`. - -If a Resource\'s templates should not be run through the Smarty -compiler, the Custom Resource may extend `Smarty_Resource_Uncompiled`. -The Resource Handler must then implement the function -`renderUncompiled(Smarty_Internal_Template $_template)`. `$_template` is -a reference to the current template and contains all assigned variables -which the implementor can access via -`$_template->smarty->getTemplateVars()`. These Resources simply echo -their rendered content to the output stream. The rendered output will be -output-cached if the Smarty instance was configured accordingly. See -`libs/sysplugins/smarty_internal_resource_php.php` for an example. - -If the Resource\'s compiled templates should not be cached on disk, the -Custom Resource may extend `Smarty_Resource_Recompiled`. These Resources -are compiled every time they are accessed. This may be an expensive -overhead. See `libs/sysplugins/smarty_internal_resource_eval.php` for an -example. - - - <?php - - /** - * MySQL Resource - * - * Resource Implementation based on the Custom API to use - * MySQL as the storage resource for Smarty's templates and configs. - * - * Table definition: - * <pre>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;</pre> - * - * Demo data: - * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre> - * - * @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"); - ?> - - - -And from within Smarty template: - - - {include file='mysql:extras/navigation.tpl'} - - - -See also [`registerResource()`](#api.register.resource), -[`unregisterResource()`](#api.unregister.resource). diff --git a/docs/programmers/plugins/plugins-writing.md b/docs/programmers/plugins/plugins-writing.md deleted file mode 100644 index 972911d9..00000000 --- a/docs/programmers/plugins/plugins-writing.md +++ /dev/null @@ -1,36 +0,0 @@ -Writing Plugins {#plugins.writing} -=============== - -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: - - - <?php - function smarty_function_yourPlugin(array $params, Smarty_Internal_Template $template) - { - // load plugin depended upon - $template->smarty->loadPlugin('smarty_shared_make_timestamp'); - // plugin code - } - ?> - - - -As a general rule, the currently evaluated template\'s -Smarty\_Internal\_Template object is always passed to the plugins as the -last parameter with two exceptions: - -- modifiers do not get passed the Smarty\_Internal\_Template object at - all - -- blocks get passed `$repeat` after the Smarty\_Internal\_Template - object to keep backwards compatibility to older versions of Smarty. diff --git a/docs/programmers/resources.md b/docs/programmers/resources.md deleted file mode 100644 index 23969006..00000000 --- a/docs/programmers/resources.md +++ /dev/null @@ -1,19 +0,0 @@ -Resources -========= - -The templates may come from a variety of sources. When you -[`display()`](./api-functions/api-display.md) or [`fetch()`](./api-functions/api-fetch.md) 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. If a -resource is not explicitly given, the value of -[`$default_resource_type`](./api-variables/variable-default-resource-type.md) (default: -\"file\") is assumed. - -## Table of contents - -- [File Template Resources](./resources/resources-file.md) -- [String Template Resources](./resources/resources-string.md) -- [Stream Template Resources](./resources/resources-streams.md) -- [Extends Template Resources](./resources/resources-extends.md) -- [Custom Template Resources](./resources/resources-custom.md) - diff --git a/docs/programmers/resources/resources-custom.md b/docs/programmers/resources/resources-custom.md deleted file mode 100644 index d679afcb..00000000 --- a/docs/programmers/resources/resources-custom.md +++ /dev/null @@ -1,111 +0,0 @@ -Custom Template Resources {#resources.custom} -========================= - -You can retrieve templates using whatever possible source you can access -with PHP: databases, sockets, files, etc. You do this by writing -resource plugin functions and registering them with Smarty. - -See [resource plugins](#plugins.resources) section for more information -on the functions you are supposed to provide. - -> **Note** -> -> 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. - - - <?php - - /** - * MySQL Resource - * - * Resource Implementation based on the Custom API to use - * MySQL as the storage resource for Smarty's templates and configs. - * - * Table definition: - * <pre>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;</pre> - * - * Demo data: - * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre> - * - * @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"); - ?> - - - -And from within Smarty template: - - - {include file='mysql:extras/navigation.tpl'} - - diff --git a/docs/programmers/resources/resources-extends.md b/docs/programmers/resources/resources-extends.md deleted file mode 100644 index d7213d89..00000000 --- a/docs/programmers/resources/resources-extends.md +++ /dev/null @@ -1,36 +0,0 @@ -Extends Template Resources {#resources.extends} -========================== - -The `extends:` resource is used to define child/parent relationships for -template inheritance from the PHP script. For details see section of -[Template Inheritance](#advanced.features.template.inheritance). - -As of Smarty 3.1 the `extends:` resource may use any available [template -resource](#resources), including `string:` and `eval:`. When [templates -from strings](#resources.string) are used, make sure they are properly -(url or base64) encoded. Is an `eval:` resource found within an -inheritance chain, its \"don\'t save a compile file\" property is -superseded by the `extends:` resource. The templates within an -inheritance chain are not compiled separately, though. Only a single -compiled template will be generated. - -> **Note** -> -> Use this when inheritance is required programmatically. When inheriting -> within PHP, it is not obvious from the child template what inheritance -> took place. If you have a choice, it is normally more flexible and -> intuitive to handle inheritance chains from within the templates. - - - <?php - $smarty->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}'); - ?> - - - -See also [Template Inheritance](#advanced.features.template.inheritance) -[`{block}`](#language.function.block) and -[`{extends}`](#language.function.extends). diff --git a/docs/programmers/resources/resources-file.md b/docs/programmers/resources/resources-file.md deleted file mode 100644 index 9a89af18..00000000 --- a/docs/programmers/resources/resources-file.md +++ /dev/null @@ -1,160 +0,0 @@ -File Template Resources {#resources.file} -======================= - -Smarty ships with a built-in template resource for the filesystem. The -`file:` is the default resource. The resource key `file:` must only be -specified, if the -[`$default_resource_type`](#variable.default.resource.type) has been -changed. - -If the file resource cannot find the requested template, the -[`$default_template_handler_func`](#variable.default.template.handler.func) -is invoked. - -> **Note** -> -> As of Smarty 3.1 the file resource no longer walks through the -> [include\_path](https://www.php.net/ini.core.php#ini.include-path) unless -> [`$use_include_path` is activated](#variable.use.include.path) - -Templates from \$template\_dir {#templates.from.template.dir} ------------------------------- - -The file resource pulls templates source files from the directories -specified in [`$template_dir`](#variable.template.dir). The list of -directories is traversed in the order they appear in the array. The -first template found is the one to process. - - - <?php - $smarty->display('index.tpl'); - $smarty->display('file:index.tpl'); // same as above - ?> - - - -From within a Smarty template - - - {include file='index.tpl'} - {include file='file:index.tpl'} {* same as above *} - - - -Templates from a specific \$template\_dir {#templates.from.specified.template.dir} ------------------------------------------ - -Smarty 3.1 introduced the bracket-syntax for specifying an element from -[`$template_dir`](#variable.template.dir). This allows websites -employing multiple sets of templates better control over which template -to access. - -The bracket-syntax can be used from anywhere you can specify the `file:` -resource type. - - - <?php - - // setup template directories - $smarty->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 - - ?> - - - -From within a Smarty template - - - {include file="file:foo.tpl"} - {* will load ./templates/foo.tpl *} - - {include file="file:[1]foo.tpl"} - {* will load ./templates_2/foo.tpl *} - - {include file="file:[foo]foo.tpl"} - {* will load ./templates_foo/foo.tpl *} - - - -Templates from any directory {#templates.from.any.dir} ----------------------------- - -Templates outside of the [`$template_dir`](#variable.template.dir) -require the `file:` template resource type, followed by the absolute -path to the template (with leading slash.) - -> **Note** -> -> With [`Security`](#advanced.features.security) enabled, access to -> templates outside of the [`$template_dir`](#variable.template.dir) is -> not allowed unless you list those directories in `$secure_dir`. - - - <?php - $smarty->display('file:/export/templates/index.tpl'); - $smarty->display('file:/path/to/my/templates/menu.tpl'); - ?> - - - -And from within a Smarty template: - - - {include file='file:/usr/local/share/templates/navigation.tpl'} - - - -Windows Filepaths {#templates.windows.filepath} ------------------ - -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. - - - <?php - $smarty->display('file:C:/export/templates/index.tpl'); - $smarty->display('file:F:/path/to/my/templates/menu.tpl'); - ?> - - - -And from within Smarty template: - - - {include file='file:D:/usr/local/share/templates/navigation.tpl'} diff --git a/docs/programmers/resources/resources-streams.md b/docs/programmers/resources/resources-streams.md deleted file mode 100644 index e0596f59..00000000 --- a/docs/programmers/resources/resources-streams.md +++ /dev/null @@ -1,27 +0,0 @@ -Stream Template Resources {#resources.streams} -========================= - -Streams allow you to use PHP streams as a template resource. The syntax -is much the same a traditional template resource names. - -Smarty will first look for a registered template resource. If nothing is -found, it will check if a PHP stream is available. If a stream is -available, Smarty will use it to fetch the template. - -> **Note** -> -> You can further define allowed streams with security enabled. - -Using a PHP stream for a template resource from the display() function. - - - $smarty->display('foo:bar.tpl'); - - - -Using a PHP stream for a template resource from within a template. - - - {include file="foo:bar.tpl"} - - diff --git a/docs/programmers/resources/resources-string.md b/docs/programmers/resources/resources-string.md deleted file mode 100644 index d3f6d415..00000000 --- a/docs/programmers/resources/resources-string.md +++ /dev/null @@ -1,73 +0,0 @@ -String Template Resources {#resources.string} -========================= - -Smarty can render templates from a string by using the `string:` or -`eval:` resource. - -- The `string:` resource behaves much the same as a template file. The - template source is compiled from a string and stores the compiled - template code for later reuse. Each unique template string will - create a new compiled template file. If your template strings are - accessed frequently, this is a good choice. If you have frequently - changing template strings (or strings with low reuse value), the - `eval:` resource may be a better choice, as it doesn\'t save - compiled templates to disk. - -- The `eval:` resource evaluates the template source every time a page - is rendered. This is a good choice for strings with low reuse value. - If the same string is accessed frequently, the `string:` resource - may be a better choice. - -> **Note** -> -> With a `string:` resource type, each unique string generates a -> compiled file. Smarty cannot detect a string that has changed, and -> therefore will generate a new compiled file for each unique string. It -> is important to choose the correct resource so that you do not fill -> your disk space with wasted compiled strings. - - - <?php - $smarty->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 - ?> - - - -From within a Smarty template - - - {include file="string:$template_string"} {* compiles for later reuse *} - {include file="eval:$template_string"} {* compiles every time *} - - - - -Both `string:` and `eval:` resources may be encoded with -[`urlencode()`](https://www.php.net/urlencode) or -[`base64_encode()`](https://www.php.net/urlencode). This is not necessary -for the usual use of `string:` and `eval:`, but is required when using -either of them in conjunction with -[`Extends Template Resource`](#resources.extends) - - - <?php - $smarty->assign('foo','value'); - $template_string_urlencode = urlencode('display {$foo} here'); - $template_string_base64 = base64_encode('display {$foo} here'); - $smarty->display('eval:urlencode:'.$template_string_urlencode); // will decode string using urldecode() - $smarty->display('eval:base64:'.$template_string_base64); // will decode string using base64_decode() - ?> - - - -From within a Smarty template - - - {include file="string:urlencode:$template_string_urlencode"} {* will decode string using urldecode() *} - {include file="eval:base64:$template_string_base64"} {* will decode string using base64_decode() *} - - - diff --git a/docs/programmers/resources/template-resources.md b/docs/programmers/resources/template-resources.md deleted file mode 100644 index 7bb5d752..00000000 --- a/docs/programmers/resources/template-resources.md +++ /dev/null @@ -1,130 +0,0 @@ -Resources {#resasdources} -========= - -The templates may come from a variety of sources. When you -[`display()`](#api.display) or [`fetch()`](#api.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. If a -resource is not explicitly given, the value of -[`$default_resource_type`](#variable.default.resource.type) is assumed. - -Templates from other sources {#templates.from.elsewhere} ----------------------------- - -You can retrieve templates using whatever possible source you can access -with PHP: databases, sockets, files, etc. You do this by writing -resource plugin functions and registering them with Smarty. - -See [resource plugins](#plugins.resources) section for more information -on the functions you are supposed to provide. - -> **Note** -> -> 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. - - - <?php - - /** - * MySQL Resource - * - * Resource Implementation based on the Custom API to use - * MySQL as the storage resource for Smarty's templates and configs. - * - * Table definition: - * <pre>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;</pre> - * - * Demo data: - * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre> - * - * @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"); - ?> - - - -And from within Smarty template: - - - {include file='mysql:extras/navigation.tpl'} - - - -Default template handler function {#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. - -See also [`Streams`](#advanced.features.streams) diff --git a/docs/programmers/smarty-constants.md b/docs/programmers/smarty-constants.md deleted file mode 100644 index de04e1b5..00000000 --- a/docs/programmers/smarty-constants.md +++ /dev/null @@ -1,26 +0,0 @@ -Constants {#smarty.constants} -========= - -SMARTY\_DIR {#constant.smarty.dir} -=========== - -This is the **full system path** to the location of the Smarty class -files. If this is not defined in your script, then Smarty will attempt -to determine the appropriate value automatically. If defined, the path -**must end with a trailing slash/**. - - - <?php - // set path to Smarty directory *nix style - define('SMARTY_DIR', '/usr/local/lib/php/Smarty-v.e.r/libs/'); - - // path to Smarty windows style - define('SMARTY_DIR', 'c:/webroot/libs/Smarty-v.e.r/libs/'); - - // include the smarty class, note 'S' is upper case - require_once(SMARTY_DIR . 'Smarty.class.php'); - ?> - - - -See also [`$smarty.const`](../designers/language-variables/language-variables-smarty.md). |
