* WIP converting code to PSR-4

* More PSR4 rewriting

* Removed autoload filters

* WIP making compile classes PSR-4

* WIP making compile classes PSR-4

* Replace Smarty:: with symfony/polyfill-mbstring

* WIP making compile classes PSR-4

* finished rewriting all compile classes into PSR-4

* Rewrote all Compile and Compiler classes to PSR-4

* WIP rewriting smarty_internal_method_*

* Finished moving smarty_internal_method_*

* smarty_internal_resource_* to PSR-4

* Refactored all _runtime_* by merging them into the proper classes or by transforming them into Runtime Extensions.

* src/Template/* to PSR-4

* src/sysplugins/* to PSR-4

* Entire src dir now PSR-4 compatible

* Add makefile, PSR-4 ModifierCompilers

* Rewrote all default modifiers and functions from the plugins folder to PSR-4 classes

* Rewrote remaining plugins to PSR-4, plugins dir is now gone.

* WIP moving Smarty to PSR-4.

* fixed pre/post/output filters and removed some old todo-comments

* filter tests passing

* Fixed TemplateObject test

* Fix CustomResourceAmbiguousTest

* Fixed CacheResource implementation and tests

* Fixed setfilter

* Fixed DefaultPluginHandlerTest for function plugins (blocks still break)

* move runPluginFromDefaultHandler to new Runtime class

* Introduce formatParamsArray method for recurring code fragment

* Fix code duplication in block compilers and fix (most) BlockPluginTests. Default plugin handler blocks still need fixing.

* minor fixes

* Implemented the DefaultHandlerBlockCompiler, made the dependencies of the template compiler into properties, fixed a couple of unit tests

* Removed support for PHP include path, and removed the ::loadPlugin method.

* Removed now unneeded PHPunit annotations @run(Tests)InSeparateProcess, @preserveGlobalState and @backupStaticAttributes. Made CacheResourceTestCommon abstract to prevent the base class from running tests (and always failing). Unregister a previously registered stream wrapper. Fixes a lot of tests.

* Fix scoping / global state problems in tests by using DI in Default Extension. Also removing a bunch of old fashioned phpdoc annotations that are superseded by namespaces.

* Make DefaultExtension lazy load again.

* Removed deprecated extends_recursion property and fix bug in CodeFrame compiler due to use of clone.

* Fixed BC loading of resource pluging from dir and all ResourcePluginTest tests

* Removed PHP functions and checks for the already removed php modifiers. Re-implemented functions as regular functions. Probably should compile these directly.

* Fixed stream resources

* 2 small fixes for unit tests

* Fixed modifiercompiler handling multiple/chained modifiers

* Rewrote global static global_tpl_vars to getters/setters on Smarty class, fixing several test cases. Added a ::getValue() method to Variable.

* Fixed issue related to scoping of left/right delimiter overrides

* Added strlen function, fixing some unit tests

* Fix bug in calling BC function handlers.

* WIP replacing direct access tpl_vars with proper getter/setters.

* WIP

* WIP rewriting variable scopes

* WIP fixing the complicated variables scopes architecture. Right now more tests are failing than before... :(

* Fixed minor unit tests

* Made variable scoping more sensible

* Fix configfile tests

* removed phpplugin, removed now unused uncompiled handler and all checks for this, fixed a refactorbug in InheritanceRuntime. Moved getRenderedTemplateCode method to Smarty\Template. Renamed Cache en Compiled base class to GeneratedPhpFile for more clarity and distinction from Resource classes. Inlined Cached::create into its only caller. Some other minor improvements. Removed php7.1 CI tests.

* Removed the allowUndefinedVars check from the smarty error handlers, because undefined vars no longer throw an error, unless smarty->error_unassigned is set to true.

* Replace direct access to inheritance property on Template object by proper getter.

* converted 3 public properties on Template into getters/setters. unified Template creation code. Provided a getter/setter for the has_nocache_code property. Removed the useless DataObject class. Fixed a few tests. Removed the variable-allow-php-templates property from the docs.

* Simplified the (no)caching architecture by:
- removing support for $cache_attrs for registered plugins,
- removing the undocumented {make_nocache} tag and the deprecated {insert} tag and associated code
- removing support for a compile_id property on include tags.

Fixes a bug in extends: resources by propagating the nocache-hashes between a master template and it's subtemplates in \Smarty\Template::_subTemplateRender. This might need further improvement.

* Removed unneeded magic setters/getters/destructors and the like.

* Replaced a bunch of direct property access with getters/setters.

* Update test runners: no longer support PHP7.1, add PHP8.2

* Fixed scope in variable assignments in included and extended templates, fixed dependencies for testing freshness of caches. Added some unit tests and fixed a class reference to pass some more tests.

* Fix searchParents parameter, fixing GetTemplateVarsTest

* @var integer > @var int for vsCode

* Fix function caching function name

* Fixed cacheability of block plugins.

* Moved handling of smarty.block.* to special compilers, because they aren't real tags. Organized tag-stack handling in compiler, unified nocache handling in compiler.

* Fixed block append/prepend functionality

* Fix testRegisterCompilerFunction by parsing argument correctly.

* Made exception msgs exactly the same again, fixing some unit tests

* Fix default plugin handler

* Simply the "isFresh" method by not including the first param anymore. Fix a couple of unit tests by respecting tag_nocache set by nocache vars used in a tag.

* Removed the undocumented {block_parent} and {parent} alternatives to {$smarty.block.parent}
and {block_child} and {child} alternatives to {$smarty.block.child}

* Fix inhertiance implementation for $smarty.block.child

* Fixed all inheritance issues

* Handle BC registered compilers and missed parameters for openTag and closeTag.

* Fix all foreach unit tests

* Fixed the {if} failures.

* Fix major {include} bug

* Fixed bug in {include} variable assignment and removed some unused/unrequired code

* Fix function call compilation using {functionname} syntax for in-template defined functions.

* Drop a unit tests bc we no longer support direct access to PHP-functinos such as sin()

* Fixed all scope assignment bugs

* Convert isset and empty to modifiercomilers, and smooth the error handling to fix unit tests.

* Fixed getCachedContent

* Add TODO list

* Run composer install before online test run

* Attempt to fix CI

* revise CI/CD workflows, bypass packagist for lexer

* Update ci.yml

* Update ci.yml

* fixes in source files

* Update ci.yml

* Update ci.yml

* attempt to load smarty-lexer directly from zip file

* Shouldnt need Github token now

* correct type of repository

* Updated the changelog

* Re-organized rendering (read source / compile / cache) process to avoid circular dependencies.
Deactivated merge_compiled_includes and the {include inline} attribute. They don't seem to do much in terms of performance, but we'll
have to check back.

* updated todo

* Fix smarty-lexer dependency for the time being

* Fix smarty-lexer dependency for the time being (remove direct ref to github)

* Pushed Lexers/Parsers into VCS again in order to be able to deliver using Packagist/Composer

* Re-organized rendering (read source / compile / cache) process to avoid circular dependencies.

* Run make regardless of timestamps, so we are sure unit tests run with the generated PHP code, not with accidental human made changes to Lexer/Parser.

* Update composer packages cache key

Update composer packages cache key to trigger refresh on lexer

* 4.0.2 of smarty-lexer is released, use that

* Throw compile error when using a modifier where it won't work. Fixes #526.

* verify that native PHP functions cannot be used as a modifier and verify that an easy userland workaround exists. Fixes #813.

* Add test for registering compiler plugin with positional params. Fixes #164

* move test methods because some other test methods rely on their relative positions

* Smarty no longer calls `mb_internal_encoding()` and doesn't check for deprecated `mbstring.func_overload` ini directive.
Fixes #480.

* Generated `<script>` tags lo longer have deprecated `type="text/javascript"` or `language="Javascript"` attributes.
Fixes #815.

* Fix error in docs on prepend/append. Fixes #818.

* Move all creating of templates to Smarty::createTemplate, adding a private property containing previously generated templates for speed.

* Load compiled object in template constructor so it will be cached.

* WIP for performance improvements.

Removed $smarty->_current_file and $smarty->allow_ambiguous_resources properties, both unused. Removed public Source::filepath property.
Cached an Compiled files (and Exceptions) no longer rely on the filepath being set. Removed explicit tests for cached and compiled filenames. The exact implementation is not important. Added tests for compile_check property, fixing a file_exists check that would always be done on source template files, even when compile_check was true. Remove code duplication between Source en Config classes. Added a local $_smarty_current_dir to the generated code files for backwards compatability for {$smarty.current_dir}.

* remove additional calls to getCached()

* updated todo

* Add mkdocs for docs

* add missing folder for unit tests

* Revert latest CI changes, we'll update docs by hand for now

* multiversion mkdocs config

* fixes to docs

* WIP improving the docs

* Improved another chunk of the designers docs

* Finished improving designers docs

* Update code examples to use Smarty\Smarty and autoload instead of require_once calls and new Smarty

* Further WIP improving docs

* Updated changelog and todo list

* WIP on API docs

* WIP docs (added page on config)

* Fixed markdown syntax. Fixes #879

* Added full support and documentation for ternary operator.
Fixes #881

* updated changelog

* fixed error in the mkdocs TOC

* Added support for null coalescing operator
Fixes #882

* Add docs for null coalescing

* more docs

* Improved docs on compile checking and inheritance

* Rewrote docs on filters and resources.

* Add makefile entries for generating docs

* Docs on caching

* finished docs on security and extending smarty

* Added Smarty::setExtensions(), fixed unit test for the null coalescing operator. Updated docs about registering a custom extension.

* updated todos

* fix template invalidation when migrating to 5.0
This commit is contained in:
Simon Wisselink
2023-08-08 00:04:14 +02:00
committed by GitHub
parent a3cbdc46fb
commit 8fd949ac5d
771 changed files with 27126 additions and 36092 deletions
+92
View File
@@ -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 &amp; ME Corp.</small>
```
Note how the [escape modifier](../designers/language-modifiers/language-modifier-escape.md)
translated the `&` character into the proper HTML syntax `&amp;`.
+184
View File
@@ -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);
```
+36
View File
@@ -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());
```
@@ -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');
```
+175
View File
@@ -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();
```
+59
View File
@@ -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}
```
+101
View File
@@ -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(),
]);
```
+10
View File
@@ -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).
+27
View File
@@ -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}
```
+84
View File
@@ -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';
```
+35
View File
@@ -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');
```
+33
View File
@@ -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... *}
```
+26
View File
@@ -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');
```
+130
View File
@@ -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');
```
+86
View File
@@ -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');
```
+322
View File
@@ -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');
```
+119
View File
@@ -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.
+139
View File
@@ -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 &amp; 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.
+89
View File
@@ -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)
+106
View File
@@ -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}
```
@@ -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}
```
+13
View File
@@ -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)