Compare commits

..

5 Commits

Author SHA1 Message Date
Simon Wisselink 4c9b156d8b some link fixes 2021-12-03 11:56:44 +01:00
Simon Wisselink 313707df94 Added TOCs, rewrote most important links in documentation. Linked README to new Github Pages site 2021-12-03 11:47:39 +01:00
Simon Wisselink ea5f03e2e2 Removed BC docs, added TOC 2021-12-03 10:38:26 +01:00
Simon Wisselink d5d2e69d04 Set theme jekyll-theme-minimal 2021-12-03 10:16:00 +01:00
Simon Wisselink 845523e684 Add converted docs repo 2021-12-03 10:13:31 +01:00
746 changed files with 33610 additions and 25952 deletions
+2 -4
View File
@@ -7,10 +7,8 @@
# exclude from git export
/tests export-ignore
/utilities export-ignore
/docker-compose.yml export-ignore
/.github export-ignore
/run_tests_for_all_php_versions.sh export-ignore
/utilities/ export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/make-release.sh export-ignore
+13 -21
View File
@@ -1,10 +1,8 @@
# https://help.github.com/en/categories/automating-your-workflow-with-github-actions
on:
pull_request:
push:
branches:
- 'master'
- pull_request
- push
name: CI
@@ -25,12 +23,11 @@ jobs:
- ubuntu-latest
php-version:
- "7.1"
- "7.2"
- "7.3"
- "7.4"
- "8.0"
- "8.1"
- "8.2"
compiler:
- default
@@ -39,16 +36,10 @@ jobs:
- os: ubuntu-latest
php-version: "8.0"
compiler: jit
- os: ubuntu-latest
php-version: "8.1"
compiler: jit
- os: ubuntu-latest
php-version: "8.2"
compiler: jit
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v2
- name: Override PHP ini values for JIT compiler
if: matrix.compiler == 'jit'
@@ -62,20 +53,21 @@ jobs:
extensions: ${{ env.PHP_EXTENSIONS }}
ini-values: ${{ env.PHP_INI_VALUES }}
- name: Validate composer.json and composer.lock
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
uses: actions/cache@v2
with:
path: vendor
key: v5r2-${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
key: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
v5r1-${{ runner.os }}-php-${{ matrix.php-version }}-
${{ runner.os }}-php-${{ matrix.php-version }}-
- name: Install dependencies
uses: php-actions/composer@v6
- name: Run make
run: make -B
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Run tests with phpunit
run: php ./vendor/phpunit/phpunit/phpunit
run: ./phpunit.sh
+9 -2
View File
@@ -1,7 +1,14 @@
.idea/
# Smarty
lexer/*.php
lexer/*.php.bak
lexer/*.out
utilies/*.php
# Dev
phpunit*
.phpunit.result.cache
/vendor/*
/composer.lock
vendor/*
composer.lock
+2 -136
View File
@@ -6,140 +6,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- Added support for PHP8.2
### Changed
- All Smarty code is now in the \Smarty namespace. For simple use-cases, you only need to add
`use \Smarty\Smarty;` to your script and everything will work. If you extend Smarty or use
Smarty plug-ins, please review your code to see if they assume specific class or method names.
E.g.: `Smarty_Internal_Template` is now `\Smarty\Template\`, `SmartyException` is now `\Smarty\Exception`.
- Template variable scope bubbling has been simplified and made more consistent.
The global scope now equals the Smarty scope in order to avoid global state side effects. Please read
the documentation for more details.
- Lexers and Parsers PHP files are no longer under version control, but generated from sources (.y and .plex)
- Smarty now always runs in multibyte mode, using `symfony/polyfill-mbstring` if required. Please use the
multibyte extension for optimal performance.
### Deprecated
- `$smarty->getPluginsDir()`
- `$smarty->loadFilter()`
- `$smarty->setPluginsDir()`
- `$smarty->assignGlobal()`
- Using `$smarty->registerFilter()` for registering variable filters will trigger a notice.
-
### Removed
- Dropped support for PHP7.1
- Removed `$smarty->left_delimiter` and `$smarty->right_delimiter`, use `$smarty->getLeftDelimiter()`/`$smarty->setLeftDelimiter()` and `$smarty->getRightDelimiter()`/`$smarty->setRightDelimiter()`
- Removed support for the `$cache_attrs` parameter for registered plugins
- Removed support for undocumented `{make_nocache}` tag
- Removed support for deprecated `{insert}` tag, the 'insert' plugin type and the associated $smarty->trusted_dir variable
- Removed the undocumented `{block_parent}` and `{parent}` alternatives to `{$smarty.block.parent}`
- Removed the undocumented `{block_child}` and `{child}` alternatives to `{$smarty.block.child}`
- Removed support for loading config files into a non-local scope using `{config_load}` from a template
- Removed `$smarty->autoload_filters` in favor of `$smarty->registerFilter()`
- Removed `$smarty->trusted_dir` and `$smarty->allow_php_templates` since support for executing php scripts from templates has been dropped
- Removed `$smarty->php_functions` and `$smarty->php_modifiers`. If you need a PHP-function in your templates,
register it as a modifier.
- Removed support for `$smarty->getTags()`
- Removed the abandoned `$smarty->direct_access_security` setting
- Dropped support for `$smarty->plugins_dir` and `$smarty->use_include_path`. If you must, use `$smarty->addPluginsDir()` instead,
but it's better to use Smarty::addExtension() to add an extension or Smarty::registerPlugin to
quickly register a plugin using a callback function.
- Removed constants such as SMARTY_DIR to prevent global side effects.
- Removed direct access to `$smarty->template_dir`. Use `$smarty->setTemplateDir()`.
- Removed direct access to `$smarty->cache_dir`. Use `$smarty->setCacheDir()`.
- Removed `$smarty->loadPlugin()`, use `$smarty->registerPlugin()` instead.
- Removed `$smarty->appendByRef()` and `$smarty->assignByRef()`.
- Removed `$smarty->use_sub_dirs`. Cached files are now automatically stored in subdirs for maximum performance.
### Fixed
- `$smarty->muteUndefinedOrNullWarnings()` now also mutes PHP7 notices for undefined array indexes [#736](https://github.com/smarty-php/smarty/issues/736)
- `$smarty->muteUndefinedOrNullWarnings()` now treats undefined vars and array access of a null or false variables
equivalent across all supported PHP versions
- `$smarty->muteUndefinedOrNullWarnings()` now allows dereferencing of non-objects across all supported PHP versions [#831](https://github.com/smarty-php/smarty/issues/831)
- PHP 8.1 deprecation warnings on null strings in modifiers [#834](https://github.com/smarty-php/smarty/pull/834)
## [4.3.0] - 2022-11-22
### Added
- PHP8.2 compatibility [#775](https://github.com/smarty-php/smarty/pull/775)
### Changed
- Include docs and demo in the releases [#799](https://github.com/smarty-php/smarty/issues/799)
- Using PHP functions as modifiers now triggers a deprecation notice because we will drop support for this in the next major release [#813](https://github.com/smarty-php/smarty/issues/813)
- Dropped remaining references to removed PHP-support in Smarty 4 from docs, lexer and security class. [#816](https://github.com/smarty-php/smarty/issues/816)
- Support umask when writing (template) files and set dir permissions to 777 [#548](https://github.com/smarty-php/smarty/issues/548) [#819](https://github.com/smarty-php/smarty/issues/819)
### Fixed
- Output buffer is now cleaned for internal PHP errors as well, not just for Exceptions [#514](https://github.com/smarty-php/smarty/issues/514)
- Fixed recursion and out of memory errors when caching in complicated template set-ups using inheritance and includes [#801](https://github.com/smarty-php/smarty/pull/801)
- Fixed PHP8.1 deprecation errors in strip_tags
- Fix Variable Usage in Exception message when unable to load subtemplate [#808](https://github.com/smarty-php/smarty/pull/808)
- Fixed PHP8.1 deprecation notices for strftime [#672](https://github.com/smarty-php/smarty/issues/672)
- Fixed PHP8.1 deprecation errors passing null to parameter in trim [#807](https://github.com/smarty-php/smarty/pull/807)
- Adapt Smarty upper/lower functions to be codesafe (e.g. for Turkish locale) [#586](https://github.com/smarty-php/smarty/pull/586)
- Bug fix for underscore and limited length in template name in custom resources [#581](https://github.com/smarty-php/smarty/pull/581)
## [4.2.1] - 2022-09-14
### Security
- Applied appropriate javascript and html escaping in mailto plugin to counter injection attacks [#454](https://github.com/smarty-php/smarty/issues/454)
### Fixed
- Fixed PHP8.1 deprecation notices in modifiers (upper, explode, number_format and replace) [#755](https://github.com/smarty-php/smarty/pull/755) and [#788](https://github.com/smarty-php/smarty/pull/788)
- Fixed PHP8.1 deprecation notices in capitalize modifier [#789](https://github.com/smarty-php/smarty/issues/789)
- Fixed use of `rand()` without a parameter in math function [#794](https://github.com/smarty-php/smarty/issues/794)
- Fixed unselected year/month/day not working in html_select_date [#395](https://github.com/smarty-php/smarty/issues/395)
## [4.2.0] - 2022-08-01
### Fixed
- Fixed problems with smarty_mb_str_replace [#549](https://github.com/smarty-php/smarty/issues/549)
- Fixed second parameter of unescape modifier not working [#777](https://github.com/smarty-php/smarty/issues/777)
### Changed
- Updated HTML of the debug template [#599](https://github.com/smarty-php/smarty/pull/599)
## [4.1.1] - 2022-05-17
### Security
- Prevent PHP injection through malicious block name or include file name. This addresses CVE-2022-29221
### Fixed
- Exclude docs and demo from export and composer [#751](https://github.com/smarty-php/smarty/pull/751)
- PHP 8.1 deprecation notices in demo/plugins/cacheresource.pdo.php [#706](https://github.com/smarty-php/smarty/issues/706)
- PHP 8.1 deprecation notices in truncate modifier [#699](https://github.com/smarty-php/smarty/issues/699)
- Math equation `max(x, y)` didn't work anymore [#721](https://github.com/smarty-php/smarty/issues/721)
- Fix PHP 8.1 deprecated warning when calling rtrim [#743](https://github.com/smarty-php/smarty/pull/743)
- PHP 8.1: fix deprecation in escape modifier [#727](https://github.com/smarty-php/smarty/pull/727)
## [4.1.0] - 2022-02-06
### Added
- PHP8.1 compatibility [#713](https://github.com/smarty-php/smarty/pull/713)
## [4.0.4] - 2022-01-18
### Fixed
- Fixed illegal characters bug in math function security check [#702](https://github.com/smarty-php/smarty/issues/702)
## [4.0.3] - 2022-01-10
### Security
- Prevent evasion of the `static_classes` security policy. This addresses CVE-2021-21408
## [4.0.2] - 2022-01-10
### Security
- Prevent arbitrary PHP code execution through maliciously crafted expression for the math function. This addresses CVE-2021-29454
## [4.0.1] - 2022-01-09
### Security
- Rewrote the mailto function to not use `eval` when encoding with javascript
## [4.0.0] - 2021-11-25
## [4.0.0-rc.0] - 2021-10-13
@@ -1825,7 +1691,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
27.09.2011
- bugfix possible warning "attempt to modify property of non-object" in {section} (issue #34)
- added chaining to \Smarty\Data so $smarty->assign('a',1)->assign('b',2); is possible now
- added chaining to Smarty_Internal_Data so $smarty->assign('a',1)->assign('b',2); is possible now
- bugfix remove race condition when a custom resource did change timestamp during compilation
- bugfix variable property did not work on objects variable in template
- bugfix smarty_make_timestamp() failed to process DateTime objects properly
@@ -2160,7 +2026,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- optimize smarty_modified_escape for hex, hexentity, decentity.
28/12/2010
- changed $tpl_vars, $config_vars and $parent to belong to \Smarty\Data
- changed $tpl_vars, $config_vars and $parent to belong to Smarty_Internal_Data
- added Smarty::registerCacheResource() for dynamic cache resource object registration
27/12/2010
-19
View File
@@ -1,19 +0,0 @@
all: lexers parsers
lexers: src/Lexer/ConfigfileLexer.php src/Lexer/TemplateLexer.php
parsers: src/Parser/ConfigfileParser.php src/Parser/TemplateParser.php
src/Lexer/ConfigfileLexer.php: src/Lexer/ConfigfileLexer.plex
php ./utilities/make-lexer.php src/Lexer/ConfigfileLexer.plex src/Lexer/ConfigfileLexer.php
src/Lexer/TemplateLexer.php: src/Lexer/TemplateLexer.plex
php ./utilities/make-lexer.php src/Lexer/TemplateLexer.plex src/Lexer/TemplateLexer.php
src/Parser/ConfigfileParser.php: src/Parser/ConfigfileParser.y
php ./utilities/make-parser.php src/Parser/ConfigfileParser.y src/Parser/ConfigfileParser.php
src/Parser/TemplateParser.php: src/Parser/TemplateParser.y
php ./utilities/make-parser.php src/Parser/TemplateParser.y src/Parser/TemplateParser.php
clean:
rm -f src/Lexer/ConfigfileLexer.php src/Lexer/TemplateLexer.php src/Parser/ConfigfileParser.php src/Parser/TemplateParser.php
+10 -2
View File
@@ -7,7 +7,7 @@ Smarty is a template engine for PHP, facilitating the separation of presentation
Read the [documentation](https://smarty-php.github.io/smarty/) to find out how to use it.
## Requirements
Smarty v5 can be run with PHP 7.2 to PHP 8.2.
Smarty can be run with PHP 7.1 to PHP 8.0.
## Installation
Smarty versions 3.1.11 or later can be installed with [Composer](https://getcomposer.org/).
@@ -17,4 +17,12 @@ To get the latest stable version of Smarty use:
composer require smarty/smarty
````
More in the [Getting Started](./docs/getting-started.md) section of the docs.
To get the latest, unreleased version, use:
```bash
composer require smarty/smarty:dev-master
````
To get the previous stable version of Smarty, Smarty 3, use:
```bash
composer require smarty/smarty:^3
````
+1 -1
View File
@@ -2,7 +2,7 @@
## Supported Versions
Smarty currently supports the latest minor version of Smarty 3 and Smarty 4.
Smarty currently supports the latest minor version of Smarty 3 and Smarty 4. (Smarty 4 has not been released yet.)
| Version | Supported |
| ------- | ------------------ |
-48
View File
@@ -1,48 +0,0 @@
# @TODO
## Review direct variable property access
- review ->value{$index} in ForTag
- review ->(step|total|first|last|do_else|key|show|iteration|index)
- review ->tpl_vars, ->config_vars, ->value
- Re-introduce merge_compiled_includes and the {include inline} attribute?
## Beatify output
- strip <?php and ?> tags from generated output
## Review public static vars
- such as _CHARSET and _IS_WINDOWS
## Build
- add compiled lexers and parsers to Release assets automatically
## Benchmark
- benchmark to see that performance hasn't degraded
## Block / inheritance
- Consider phasing out $smarty.block.child as this reverses the inheritance hierarchy and might cause infinite loops
when combined with $smarty.block.parent
## Plugin system
- fix template security checks in one place in compiler
## Documentation
- beautify and review docs, possibly using [
Material for MkDocs ](https://squidfunk.github.io/mkdocs-material/publishing-your-site/)
## Resources
- Fix circular deps between resources and sources
```
$smarty = $this->_getSmartyObj();
[$name, $type] = \Smarty\Resource\BasePlugin::parseResourceName($config_file, $smarty->default_config_type);
$source = new Config($smarty, $config_file, $type, $name);
$source->handler->getContent($source);
```
## Unrelated / other
- review (and avoid) use of 'clone' keyword
- compiler->has_code seems silly. Why not have proper return values?
- what is 'user literal support', why are unit tests skipped?
+7 -12
View File
@@ -5,7 +5,7 @@
"keywords": [
"templating"
],
"homepage": "https://smarty-php.github.io/smarty/",
"homepage": "https://www.smarty.net",
"license": "LGPL-3.0",
"authors": [
{
@@ -27,28 +27,23 @@
],
"support": {
"issues": "https://github.com/smarty-php/smarty/issues",
"forum": "https://github.com/smarty-php/smarty/discussions"
"forum": "https://www.smarty.net/forums/"
},
"require": {
"php": "^7.2 || ^8.0",
"symfony/polyfill-mbstring": "^1.27",
"nette/php-generator": "^3.6"
"php": "^7.1 || ^8.0"
},
"autoload": {
"psr-4" : {
"Smarty\\" : "src/"
},
"files": [
"src/functions.php"
"classmap": [
"libs/"
]
},
"extra": {
"branch-alias": {
"dev-master": "5.0.x-dev"
"dev-master": "4.0.x-dev"
}
},
"require-dev": {
"phpunit/phpunit": "^8.5 || ^7.5",
"smarty/smarty-lexer": "dev-master"
"smarty/smarty-lexer": "^3.1"
}
}
+4 -4
View File
@@ -2,11 +2,11 @@
/**
* Example Application
*
* @package Example-application
*/
$smarty = new \Smarty\Smarty;
require '../libs/Smarty.class.php';
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
@@ -6,11 +6,23 @@
* memcache as the storage resource for Smarty's output caching.
* *
*
* @package CacheResource-examples
* @author Uwe Tews
*/
class Smarty_CacheResource_Apc extends \Smarty\Cacheresource\KeyValueStore
class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
{
/**
* Smarty_CacheResource_Apc constructor.
*
* @throws \Exception
*/
public function __construct()
{
// test if APC is present
if (!function_exists('apc_cache_info')) {
throw new Exception('APC Template Caching Error: APC is not installed');
}
}
/**
* Read values for a set of keys from cache
@@ -7,32 +7,30 @@
* 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
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
{
/**
* memcache instance
*
* @var Memcache
*/
private $memcache = null;
protected $memcache = null;
/**
* @return Memcache|Memcached
*/
public function getMemcache() {
if ($this->memcache === null) {
if (class_exists('Memcached')) {
$this->memcache = new Memcached();
} else {
$this->memcache = new Memcache();
}
$this->memcache->addServer('127.0.0.1', 11211);
}
return $this->memcache;
}
/**
* Smarty_CacheResource_Memcache constructor.
*/
public function __construct()
{
if (class_exists('Memcached')) {
$this->memcache = new Memcached();
} else {
$this->memcache = new Memcache();
}
$this->memcache->addServer('127.0.0.1', 11211);
}
/**
* Read values for a set of keys from cache
@@ -47,7 +45,7 @@ class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
$res = array();
foreach ($keys as $key) {
$k = sha1($key);
$res[$key] = $this->getMemcache()->get($k);
$res[$key] = $this->memcache->get($k);
}
return $res;
}
@@ -65,9 +63,9 @@ class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
foreach ($keys as $k => $v) {
$k = sha1($k);
if (class_exists('Memcached')) {
$this->getMemcache()->set($k, $v, $expire);
$this->memcache->set($k, $v, $expire);
} else {
$this->getMemcache()->set($k, $v, 0, $expire);
$this->memcache->set($k, $v, 0, $expire);
}
}
return true;
@@ -84,7 +82,7 @@ class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
{
foreach ($keys as $k) {
$k = sha1($k);
$this->getMemcache()->delete($k);
$this->memcache->delete($k);
}
return true;
}
@@ -96,6 +94,6 @@ class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
*/
protected function purge()
{
return $this->getMemcache()->flush();
return $this->memcache->flush();
}
}
@@ -1,7 +1,5 @@
<?php
use Smarty\Exception;
/**
* MySQL CacheResource
* CacheResource Implementation based on the Custom API to use
@@ -21,73 +19,68 @@ use Smarty\Exception;
* INDEX(`modified`)
* ) ENGINE = InnoDB;</pre>
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
{
/**
* @var \PDO
*/
protected $db;
/**
* @return PDO
* @throws Exception
*/
protected function db(): PDO {
static $dbConn = null;
try {
return $dbConn ?? ($dbConn = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty"));
} catch (PDOException $e) {
throw new Exception('Mysql Resource failed: ' . $e->getMessage());
}
}
/**
* @var \PDOStatement
*/
protected $fetch;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function fetchQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
}
/**
* @var \PDOStatement
*/
protected $fetchTimestamp;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function fetchTimestampQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare('SELECT modified FROM output_cache WHERE id = :id');
}
/**
* @var \PDOStatement
*/
protected $save;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function saveQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare(
'REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
/**
* Smarty_CacheResource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "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
* @throws Exception
*/
/**
* 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->fetchQuery()->execute(array('id' => $id));
$row = $this->fetchQuery()->fetch();
$this->fetchQuery()->closeCursor();
$this->fetch->execute(array('id' => $id));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$content = $row[ 'content' ];
$mtime = strtotime($row[ 'modified' ]);
@@ -112,9 +105,9 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
*/
protected function fetchTimestamp($id, $name, $cache_id, $compile_id)
{
$this->fetchTimestampQuery()->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestampQuery()->fetchColumn());
$this->fetchTimestampQuery()->closeCursor();
$this->fetchTimestamp->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestamp->fetchColumn());
$this->fetchTimestamp->closeCursor();
return $mtime;
}
@@ -132,14 +125,14 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
*/
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
{
$this->saveQuery()->execute(
$this->save->execute(
array('id' => $id,
'name' => $name,
'cache_id' => $cache_id,
'compile_id' => $compile_id,
'content' => $content,)
);
return !!$this->saveQuery()->rowCount();
return !!$this->save->rowCount();
}
/**
@@ -157,18 +150,18 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
// 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');
$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);
$where[] = 'name = ' . $this->db->quote($name);
}
// equal test compile_id
if ($compile_id !== null) {
$where[] = 'compile_id = ' . $this->db()->quote($compile_id);
$where[] = 'compile_id = ' . $this->db->quote($compile_id);
}
// range test expiration time
if ($exp_time !== null) {
@@ -178,13 +171,13 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
if ($cache_id !== null) {
$where[] =
'(cache_id = ' .
$this->db()->quote($cache_id) .
$this->db->quote($cache_id) .
' OR cache_id LIKE ' .
$this->db()->quote($cache_id . '|%') .
$this->db->quote($cache_id . '|%') .
')';
}
// run delete query
$query = $this->db()->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
$query = $this->db->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
return $query->rowCount();
}
}
@@ -1,7 +1,5 @@
<?php
use Smarty\Exception;
/**
* PDO Cache Handler
* Allows you to store Smarty Cache files into your db.
@@ -24,11 +22,12 @@ use Smarty\Exception;
* Example usage :
* $cnx = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
* $smarty->setCachingType('pdo');
* $smarty->loadPlugin('Smarty_CacheResource_Pdo');
* $smarty->registerCacheResource('pdo', new Smarty_CacheResource_Pdo($cnx, 'smarty_cache'));
*
* @author Beno!t POLASZEK - 2014
*/
class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
{
/**
* @var string[]
@@ -121,12 +120,12 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
* @param string $table : table (or view) name
* @param string $database : optional - if table is located in another db
*
* @throws \Smarty\Exception
* @throws \SmartyException
*/
public function __construct(PDO $pdo, $table, $database = null)
{
if (is_null($table)) {
throw new Exception("Table name for caching can't be null");
throw new SmartyException("Table name for caching can't be null");
}
$this->pdo = $pdo;
$this->table = $table;
@@ -197,7 +196,7 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
* @return void
* @access protected
*/
protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
protected function fetch($id, $name, $cache_id = null, $compile_id = null, &$content, &$mtime)
{
$stmt = $this->getFetchStatement($this->fetchColumns, $id, $cache_id, $compile_id);
$stmt->execute();
@@ -245,7 +244,7 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
* @return boolean success
* @access protected
*/
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
protected function save($id, $name, $cache_id = null, $compile_id = null, $exp_time, $content)
{
$stmt = $this->pdo->prepare($this->insertStatement);
$stmt->bindValue('id', $id);
@@ -323,7 +322,7 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
$where[] = 'compile_id = ' . $this->pdo->quote($compile_id);
}
// for clearing expired caches
if ($exp_time === \Smarty\Smarty::CLEAR_EXPIRED) {
if ($exp_time === Smarty::CLEAR_EXPIRED) {
$where[] = 'expire < CURRENT_TIMESTAMP';
} // range test expiration time
elseif ($exp_time !== null) {
@@ -1,12 +1,12 @@
<?php
require_once __DIR__ . '/cacheresource.pdo.php';
require_once 'cacheresource.pdo.php';
/**
* PDO Cache Handler with GZIP support
* Example usage :
* $cnx = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
* $smarty->setCachingType('pdo_gzip');
* $smarty->loadPlugin('Smarty_CacheResource_Pdo_Gzip');
* $smarty->registerCacheResource('pdo_gzip', new Smarty_CacheResource_Pdo_Gzip($cnx, 'smarty_cache'));
*
* @require Smarty_CacheResource_Pdo class
@@ -1,43 +1,38 @@
<?php
use Smarty\Exception;
use Smarty\Template;
use Smarty\Template\Source;
/**
* Extends All Resource
* Resource Implementation modifying the extends-Resource to walk
* through the template_dirs and inherit all templates of the same name
*
* @package Resource-examples
* @author Rodney Rehm
*/
class My_Resource_Extendsall extends \Smarty\Resource\ExtendsPlugin
class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends
{
/**
* populate Source Object with meta data from Resource
*
* @param Source $source source object
* @param Template $_template template object
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
public function populate(Source $source, Template $_template = null)
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$uid = '';
$sources = array();
$timestamp = 0;
foreach ($source->getSmarty()->getTemplateDir() as $key => $directory) {
foreach ($source->smarty->getTemplateDir() as $key => $directory) {
try {
$s = \Smarty\Template\Source::load(null, $source->getSmarty(),
'file:' . '[' . $key . ']' . $source->name);
$s = Smarty_Resource::source(null, $source->smarty, 'file:' . '[' . $key . ']' . $source->name);
if (!$s->exists) {
continue;
}
$sources[ $s->uid ] = $s;
$uid .= $s->filepath;
$timestamp = $s->timestamp > $timestamp ? $s->timestamp : $timestamp;
} catch (Exception $e) {
} catch (SmartyException $e) {
}
}
if (!$sources) {
@@ -49,7 +44,7 @@ class My_Resource_Extendsall extends \Smarty\Resource\ExtendsPlugin
$s = current($sources);
$source->components = $sources;
$source->filepath = $s->filepath;
$source->uid = sha1($uid . $source->getSmarty()->_joined_template_dir);
$source->uid = sha1($uid . $source->smarty->_joined_template_dir);
$source->exists = true;
$source->timestamp = $timestamp;
}
+101
View File
@@ -0,0 +1,101 @@
<?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
*
* @var \PDO
*/
protected $db;
/**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch;
/**
* prepared fetchTimestamp() statement
*
* @var \PDOStatement
*/
protected $mtime;
/**
* Smarty_Resource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "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);
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
/**
* MySQL Resource
* Resource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's templates and configs.
* Note that this MySQL implementation fetches the source and timestamps in
* a single database query, instead of two separate like resource.mysql.php does.
* 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_Mysqls extends Smarty_Resource_Custom
{
/**
* PDO instance
*
* @var \PDO
*/
protected $db;
/**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch;
/**
* Smarty_Resource_Mysqls constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "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');
}
/**
* 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;
}
}
}
+2
View File
@@ -11,6 +11,8 @@
The current date and time is {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
The value of global assigned variable $SCRIPT_NAME is {$SCRIPT_NAME}
Example of accessing server environment variable SERVER_NAME: {$smarty.server.SERVER_NAME}
The value of {ldelim}$Name{rdelim} is <b>{$Name}</b>
-39
View File
@@ -1,39 +0,0 @@
version: "2"
services:
base:
build:
context: .
dockerfile: ./utilities/testrunners/php72/Dockerfile
volumes:
- .:/app
working_dir: /app
php72:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php72/Dockerfile
php73:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php73/Dockerfile
php74:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php74/Dockerfile
php80:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php80/Dockerfile
php81:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php81/Dockerfile
php82:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php82/Dockerfile
+5
View File
@@ -0,0 +1,5 @@
BUGS
====
Check the `BUGS` file that comes with the latest distribution of Smarty,
or check the website.
+15
View File
@@ -0,0 +1,15 @@
Resources {#inforesources}
=========
Smarty\'s homepage is located at [URL.SMARTY](&url.smarty;)
- You can join the mailing list by sending an e-mail to ``. An archive
of the mailing list can be viewed at [here](&url.ml.archive;)
- Forums are at [URL.FORUMS](&url.forums;)
- The wiki is located at [URL.WIKI](&url.wiki;)
- Join the chat at [irc.freenode.net\#smarty](&url.wiki;)
- FAQ\'s are [here](&url.faq_1;) and [here](&url.faq_2;)
+65 -2
View File
@@ -188,6 +188,67 @@ See also [`{html_select_date}`](#language.function.html.select.date),
[`date_format`](#language.modifier.date.format) and
[`$smarty.now`](#language.variables.smarty.now),
WAP/WML {#tips.wap}
=======
WAP/WML templates require a php [Content-Type
header](&url.php-manual;header) to be passed along with the template.
The easist way to do this would be to write a custom function that
prints the header. If you are using [caching](#caching), that won\'t
work so we\'ll do it using the [`{insert}`](#language.function.insert)
tag; remember `{insert}` tags are not cached! Be sure that there is
nothing output to the browser before the template, or else the header
may fail.
<?php
// be sure apache is configure for the .wml extensions!
// put this function somewhere in your application, or in Smarty.addons.php
function insert_header($params)
{
// this function expects $content argument
if (empty($params['content'])) {
return;
}
header($params['content']);
return;
}
?>
your Smarty template *must* begin with the insert tag :
{insert name=header content="Content-Type: text/vnd.wap.wml"}
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<!-- begin new wml deck -->
<wml>
<!-- begin first card -->
<card>
<do type="accept">
<go href="#two"/>
</do>
<p>
Welcome to WAP with Smarty!
Press OK to continue...
</p>
</card>
<!-- begin second card -->
<card id="two">
<p>
Pretty easy isn't it?
</p>
</card>
</wml>
Componentized Templates {#tips.componentized.templates}
=======================
@@ -198,7 +259,7 @@ Smarty object, [`assign()`](#api.assign) the variables and
[`display()`](#api.display) the template. So lets say for example we
have a stock ticker on our template. We would collect the stock data in
our application, then assign these variables in the template and display
it. Now wouldn't it be nice if you could add this stock ticker to any
it. Now wouldn\'t it be nice if you could add this stock ticker to any
application by merely including the template, and not worry about
fetching the data up front?
@@ -240,7 +301,9 @@ assigning it to a template variable.
See also: [`{include}`](#language.function.include).
See also [`{include_php}`](#language.function.include.php),
[`{include}`](#language.function.include) and
[`{php}`](#language.function.php).
Obfuscating E-mail Addresses {#tips.obfuscating.email}
============================
+1 -1
View File
@@ -109,7 +109,7 @@ the corresponding error is in the template.
- This means that your application registered a custom error handler
- This means that your application registered a custom error hander
(using [set\_error\_handler()](&url.php-manual;set_error_handler))
which is not respecting the given `$errno` as it should. If, for
whatever reason, this is the desired behaviour of your custom error
+2 -1
View File
@@ -11,7 +11,8 @@ 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`. When you load the page, a Javascript console window will pop
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
up and give you the names of all the included templates and assigned
variables for the current page.
-13
View File
@@ -1,18 +1,6 @@
Basic Syntax
============
A simple Smarty template could look like this:
```html
<h1>{$title|escape}</h1>
<ul>
{foreach $cities as $city}
<li>{$city.name|escape} ({$city.population})</li>
{foreachelse}
<li>no cities found</li>
{/foreach}
</ul>
```
All Smarty template tags are enclosed within delimiters. By default
these are `{` and `}`, but they can be
[changed](../programmers/api-variables/variable-left-delimiter.md).
@@ -23,7 +11,6 @@ displayed as static content, or unchanged. When Smarty encounters
template tags, it attempts to interpret them, and displays the
appropriate output in their place.
The basis components of the Smarty syntax are:
- [Comments](./language-basic-syntax/language-syntax-comments.md)
- [Variables](./language-basic-syntax/language-syntax-variables.md)
- [Functions](./language-basic-syntax/language-syntax-functions.md)
@@ -3,7 +3,7 @@ Attributes {#language.syntax.attributes}
Most of the [functions](#language.syntax.functions) take attributes that
specify or modify their behavior. Attributes to Smarty functions are
much like HTML attributes. Static values don't have to be enclosed in
much like HTML attributes. Static values don\'t have to be enclosed in
quotes, but it is required for literal strings. Variables with or
without modifiers may also be used, and should not be in quotes. You can
even use PHP function results, plugin results and complex expressions.
@@ -10,6 +10,7 @@ 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>
@@ -16,9 +16,12 @@ Built-in Functions {#language.builtin.functions}
- [{function}](./language-builtin-functions/language-function-function.md)
- [{if},{elseif},{else}](./language-builtin-functions/language-function-if.md)
- [{include}](./language-builtin-functions/language-function-include.md)
- [{include_php}](./language-builtin-functions/language-function-include.php)
- [{insert}](./language-builtin-functions/language-function-insert.md)
- [{ldelim},{rdelim}](./language-builtin-functions/language-function-ldelim.md)
- [{literal}](./language-builtin-functions/language-function-literal.md)
- [{nocache}](./language-builtin-functions/language-function-nocache.md)
- [{php}](./language-builtin-functions/language-function-php.md)
- [{section},{sectionelse}](./language-builtin-functions/language-function-section.md)
- [{setfilter}](./language-builtin-functions/language-function-setfilter.md)
- [{strip}](./language-builtin-functions/language-function-strip.md)
@@ -17,7 +17,7 @@
var string Yes *n/a* The name of the variable being assigned
value string Yes *n/a* The value being assigned
index string No *n/a* The index for the new array element. If not specified the value is append to the end of the array.
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'smarty\'
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'global\'
**Option Flags:**
@@ -21,7 +21,7 @@ execution of a template**.
---------------- -------- ---------- --------- -----------------------------------------------------------------------
var string Yes *n/a* The name of the variable being assigned
value string Yes *n/a* The value being assigned
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'smarty\'
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'global\'
**Option Flags:**
@@ -135,6 +135,8 @@ The following functions can also *optionally* assign template variables.
[`{capture}`](#language.function.capture),
[`{include}`](#language.function.include),
[`{include_php}`](#language.function.include.php),
[`{insert}`](#language.function.insert),
[`{counter}`](#language.function.counter),
[`{cycle}`](#language.function.cycle),
[`{eval}`](#language.function.eval),
@@ -3,14 +3,14 @@
`{block}` is used to define a named area of template source for template
inheritance. For details see section of [Template
Inheritance](#advanced.features.template.inheritance).
Interitance](#advanced.features.template.inheritance).
The `{block}` template source area of a child template will replace the
corresponding areas in the parent template(s).
correponding areas in the parent template(s).
Optionally `{block}` areas of child and parent templates can be merged
into each other. You can append or prepend the parent `{block}` content
by using the `append` or `prepend` option flag with the child's `{block}`
by using the `append` or `prepend` option flag with the childs `{block}`
definition. With the {\$smarty.block.parent} the `{block}` content of
the parent template can be inserted at any location of the child
`{block}` content. {\$smarty.block.child} inserts the `{block}` content
@@ -28,6 +28,13 @@ 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.
{* we don't want to print a div tag unless content is displayed *}
{capture name="banner"}
@@ -3,7 +3,7 @@
`{extends}` tags are used in child templates in template inheritance for
extending parent templates. For details see section of [Template
Inheritance](#advanced.features.template.inheritance).
Interitance](#advanced.features.template.inheritance).
- The `{extends}` tag must be on the first line of the template.
@@ -33,5 +33,5 @@ Inheritance](#advanced.features.template.inheritance).
See also [Template Inheritance](#advanced.features.template.inheritance)
See also [Template Interitance](#advanced.features.template.inheritance)
and [`{block}`](#language.function.block).
@@ -2,7 +2,7 @@
=====
The `{for}{forelse}` tag is used to create simple loops. The following
different formats are supported:
different formarts are supported:
- `{for $var=$start to $end}` simple loop with step size of 1.
@@ -8,6 +8,10 @@ template engine. Every `{if}` must be paired with a matching `{/if}`.
functions are recognized, such as *\|\|*, *or*, *&&*, *and*,
*is\_array()*, etc.
If securty is enabled, only PHP functions from `$php_functions` property
of the securty policy are allowed. See the
[Security](#advanced.features.security) 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.
@@ -0,0 +1,74 @@
{include\_php} {#language.function.include.php}
==============
> **Note**
>
> `{include_php}` is deprecated from Smarty, use registered plugins to
> properly insulate presentation from the application code. As of Smarty
> 3.1 the `{include_php}` tags are only available from [SmartyBC](#bc).
Attribute Name Type Required Default Description
---------------- --------- ---------- --------- ----------------------------------------------------------------------------------
file string Yes *n/a* The name of the php file to include as absolute path
once boolean No *TRUE* whether or not to include the php file more than once if included multiple times
assign string No *n/a* The name of the variable that the output of include\_php will be assigned to
**Option Flags:**
Name Description
--------- ----------------------------------------
nocache Disables caching of inluded PHP script
`{include_php}` tags are used to include a php script in your template.
The path of the attribute `file` can be either absolute, or relative to
[`$trusted_dir`](#variable.trusted.dir). If security is enabled, then
the script must be located in the `$trusted_dir` path of the securty
policy. See the [Security](#advanced.features.security) section for
details.
By default, php files are only included once even if called multiple
times in the template. You can specify that it should be included every
time with the `once` attribute. Setting once to FALSE will include the
php script each time it is included in the template.
You can optionally pass the `assign` attribute, which will specify a
template variable name that the output of `{include_php}` will be
assigned to instead of displayed.
The smarty object is available as `$_smarty_tpl->smarty` within the PHP
script that you include.
The `load_nav.php` file:
<?php
// load in variables from a mysql db and assign them to the template
require_once('database.class.php');
$db = new Db();
$db->query('select url, name from navigation order by name');
$this->assign('navigation', $db->getRows());
?>
where the template is:
{* absolute path, or relative to $trusted_dir *}
{include_php file='/path/to/load_nav.php'}
{include_php '/path/to/load_nav.php'} {* short-hand *}
{foreach item='nav' from=$navigation}
<a href="{$nav.url}">{$nav.name}</a><br />
{/foreach}
See also [`{include}`](#language.function.include),
[`$trusted_dir`](#variable.trusted.dir),
[`{php}`](#language.function.php),
[`{capture}`](#language.function.capture), [template
resources](#resources) and [componentized
templates](#tips.componentized.templates)
@@ -131,7 +131,7 @@ cache lifetime of 500 seconds.
In this example included template will be cached independent of the
global caching setting.
global cahing setting.
{include 'sub_template.tpl' caching}
@@ -188,5 +188,7 @@ current template.
See also [template resources](#resources) and
See also [`{include_php}`](#language.function.include.php),
[`{insert}`](#language.function.insert),
[`{php}`](#language.function.php), [template resources](#resources) and
[componentized templates](#tips.componentized.templates).
@@ -0,0 +1,86 @@
{insert} {#language.function.insert}
========
> **Note**
>
> `{insert}` tags are deprecated from Smarty, and should not be used.
> Put your PHP logic in PHP scripts or plugin functions instead.
> **Note**
>
> As of Smarty 3.1 the `{insert}` tags are only available from
> [SmartyBC](#bc).
`{insert}` tags work much like [`{include}`](#language.function.include)
tags, except that `{insert}` tags are NOT cached when template
[caching](#caching) is enabled. They will be executed on every
invocation of the template.
Attribute Name Type Required Default Description
---------------- -------------- ---------- --------- ----------------------------------------------------------------------------------
name string Yes *n/a* The name of the insert function (insert\_`name`) or insert plugin
assign string No *n/a* The name of the template variable the output will be assigned to
script string No *n/a* The name of the php script that is included before the insert function is called
\[var \...\] \[var type\] No *n/a* variable to pass to insert function
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)), and needs to call a function to get the
banner contents.
{* 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](#variable.caching) 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`](#variable.trusted.dir). If security is enabled,
then the script must be located in the `$trusted_dir` path of the
securty policy. See the [Security](#advanced.features.security)
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](#caching) turned on, `{insert}` tags will not be
> cached. They will run dynamically every time the page is created, even
> within cached pages. This works good for things like banners, polls,
> live weather, search results, user feedback areas, etc.
See also [`{include}`](#language.function.include)
@@ -0,0 +1,45 @@
{php} {#language.function.php}
=====
> **Note**
>
> `{php}` tags are deprecated from Smarty, and should not be used. Put
> your PHP logic in PHP scripts or plugin functions instead.
> **Note**
>
> As of Smarty 3.1 the `{php}` tags are only available from
> [SmartyBC](#bc).
The `{php}` tags allow PHP code to be embedded directly into the
template. They will not be escaped, regardless of the
[`$php_handling`](#variable.php.handling) setting.
{php}
// including a php script directly from the template.
include('/path/to/display_weather.php');
{/php}
{* this template includes a {php} block that assign's the variable $varX *}
{php}
global $foo, $bar;
if($foo == $bar){
echo 'This will be sent to browser';
}
// assign a variable to Smarty
$this->assign('varX','Toffee');
{/php}
{* output the variable *}
<strong>{$varX}</strong> is my fav ice cream :-)
See also [`$php_handling`](#variable.php.handling),
[`{include_php}`](#language.function.include.php),
[`{include}`](#language.function.include),
[`{insert}`](#language.function.insert) and [componentized
templates](#tips.componentized.templates).
@@ -251,8 +251,8 @@ The above example will output:
{section}\'s can be nested as deep as you like. With nested
{section}\'s, you can access complex data structures, such as
multi-dimensional arrays. This is an example `.php` script that
assigns the arrays.
multi-dimensional arrays. This is an example `.php` script thats
assign\'s the arrays.
<?php
@@ -10,7 +10,7 @@ The filter can be:
- A variable filter plugin specified by it\'s name.
- A modifier specified by it\'s name and optional additional
- A modidier specified by it\'s name and optional additional
parameter.
`{setfilter}...{/setfilter}` blocks can be nested. The filter definition
@@ -22,7 +22,7 @@ ftp and display the contents.
>
> If security is enabled and you are fetching a file from the local
> file system, `{fetch}` will only allow files from within the
> `$secure_dir` path of the security policy. See the
> `$secure_dir` path of the securty policy. See the
> [Security](#advanced.features.security) section for details.
- If the `assign` attribute is set, the output of the `{fetch}`
@@ -19,7 +19,7 @@ automatically calculated from the image file if they are not supplied.
from. If not given, the web server\'s document root
`$_ENV['DOCUMENT_ROOT']` is used as the base. If security is
enabled, then the image must be located in the `$secure_dir` path of
the security policy. See the [Security](#advanced.features.security)
the securty policy. See the [Security](#advanced.features.security)
section for details.
- `href` is the href value to link the image to. If link is supplied,
+1 -1
View File
@@ -115,7 +115,7 @@ These parameters follow the modifier name and are separated by a `:`
- 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
`$modifiers` property of the securty policy. See the
[Security](../programmers/advanced-features/advanced-features-security.md) section for details.
See also [`registerPlugin()`](../programmers/api-functions/api-register-plugin.md), [combining
@@ -15,5 +15,5 @@ modifier](#language.modifier.to_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](#charset), [from\_charset
See also [Charset Enconding](#charset), [from\_charset
modifier](#language.modifier.from_charset).
@@ -15,5 +15,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](#charset), [from\_charset
See also [Charset Enconding](#charset), [from\_charset
modifier](#language.modifier.from_charset).
@@ -157,13 +157,13 @@ Returns the version of Smarty the template was compiled with.
----------------------
Returns block text from child template. See [Template
inheritance](#advanced.features.template.inheritance).
interitance](#advanced.features.template.inheritance).
{\$smarty.block.parent} {#language.variables.smarty.block.parent}
-----------------------
Returns block text from parent template. See [Template
inheritance](#advanced.features.template.inheritance)
interitance](#advanced.features.template.inheritance)
{\$smarty.ldelim}, {\$smarty.rdelim} {#language.variables.smarty.ldelim}
------------------------------------
-152
View File
@@ -1,152 +0,0 @@
Features
=======
Some of Smarty's features:
- It is extremely fast.
- It is efficient since the PHP parser does the dirty work.
- No template parsing overhead, only compiles once.
- It is smart about [recompiling](#variable.compile.check) only the
template files that have changed.
- You can easily create your own custom
[functions](#language.custom.functions) and [variable
modifiers](#language.modifiers), so the template language is
extremely extensible.
- Configurable template [{delimiter}](#variable.left.delimiter) tag
syntax, so you can use `{$foo}`, `{{$foo}}`, `<!--{$foo}-->`, etc.
- The [`{if}..{elseif}..{else}..{/if}`](#language.function.if)
constructs are passed to the PHP parser, so the `{if...}` expression
syntax can be as simple or as complex an evaluation as you like.
- Allows unlimited nesting of
[`sections`](#language.function.section), `if's` etc.
- Built-in [caching](#caching) support
- Arbitrary [template](#resources) sources
- [Template Inheritance](#advanced.features.template.inheritance) for
easy management of template content.
- [Plugin](#plugins) architecture
## Separation of presentation from application code
- This means templates can certainly contain logic under the condition
that it is for presentation only. Things such as
[including](./designers/language-builtin-functions/language-function-include.md) other templates,
[alternating](./designers/language-custom-functions/language-function-cycle.md) table row colors,
[upper-casing](./designers/language-modifiers/language-modifier-upper.md) a variable,
[looping](./designers/language-builtin-functions/language-function-foreach.md) over an array of data and
rendering it are examples of presentation logic.
- This does not mean however that Smarty forces a separation of
business and presentation logic. Smarty has no knowledge of which is
which, so placing business logic in the template is your own doing.
- Also, if you desire *no* logic in your templates you certainly can
do so by boiling the content down to text and variables only.
## How does it work?
Under the hood, Smarty "compiles" (basically copies and converts) the
templates into PHP scripts. This happens once when each template is
first invoked, and then the compiled versions are used from that point
forward. Smarty takes care of this for you, so the template designer
just edits the Smarty templates and never has to manage the compiled
versions. This approach keeps the templates easy to maintain, and yet
keeps execution times extremely fast since the compiled code is just
PHP. And of course, all PHP scripts take advantage of PHP op-code caches
such as APC.
## Template Inheritance
Template inheritance was introduced in Smarty 3. Before template
inheritance, we managed our templates in
pieces such as header and footer templates. This organization lends
itself to many problems that require some hoop-jumping, such as managing
content within the header/footer on a per-page basis. With template
inheritance, instead of including other templates we maintain our
templates as single pages. We can then manipulate blocks of content
within by inheriting them. This makes templates intuitive, efficient and
easy to manage. See
[Template Inheritance](./programmers/advanced-features/advanced-features-template-inheritance.md)
for more info.
## Why not use XML/XSLT syntax?
There are a couple of good reasons. First, Smarty can be used for more
than just XML/HTML based templates, such as generating emails,
javascript, CSV, and PDF documents. Second, XML/XSLT syntax is even more
verbose and fragile than PHP code! It is perfect for computers, but
horrible for humans. Smarty is about being easy to read, understand and
maintain.
## Template Security
Although Smarty insulates you from PHP, you still have the option to use
it in certain ways if you wish. Template security forces the restriction
of PHP (and select Smarty functions.) This is useful if you have third
parties editing templates, and you don't want to unleash the full power
of PHP or Smarty to them.
## Integration
Sometimes Smarty gets compared to Model-View-Controller (MVC)
frameworks. Smarty is not an MVC, it is just the presentation layer,
much like the View (V) part of an MVC. As a matter of fact, Smarty can
easily be integrated as the view layer of an MVC. Many of the more
popular ones have integration instructions for Smarty, or you may find
some help here in the forums and documentation.
## Other Template Engines
Smarty is not the only engine following the *"Separate Programming Code
from Presentation"* philosophy. For instance, Python has template
engines built around the same principles such as Django Templates and
CheetahTemplate. *Note: Languages such as Python do not mix with HTML
natively, which give them the advantage of proper programming code
separation from the outset. There are libraries available to mix Python
with HTML, but they are typically avoided.*
## What Smarty is Not
Smarty is not an application development framework. Smarty is not an
MVC. Smarty is not an alternative to Laravel, Symfony, CodeIgniter,
or any of the other application development frameworks for PHP.
Smarty is a template engine, and works as the (V)iew component of your
application. Smarty can easily be coupled to any of the engines listed
above as the view component. No different than any other software,
Smarty has a learning curve. Smarty does not guarantee good application
design or proper separation of presentation, this still needs to be
addressed by a competent developer and web designer.
## Is Smarty Right for Me?
Smarty is not meant to be a tool for every job. The important thing is
to identify if Smarty fits your needs. There are some important
questions to ask yourself:
### Template Syntax
Are you content with PHP tags mixed with HTML? Are your
web designers comfortable with PHP? Would your web designers prefer a
tag-based syntax designed for presentation? Some experience working with
both Smarty and PHP helps answer these questions.
### The Business Case
Is there a requirement to insulate the templates from
PHP? Do you have untrusted parties editing templates that you do not
wish to unleash the power of PHP to? Do you need to programmatically
control what is and is not available within the templates? Smarty
supplies these capabilities by design.
## Feature set
Does Smarty's features such as caching, template
inheritance and plugin architecture save development cycles writing code
that would be needed otherwise? Does the codebase or framework you plan
on using have the features you need for the presentation component?
## Sites using Smarty
Many well-known PHP projects make use of Smarty such as XOOPS CMS, CMS Made Simple, Tiki
CMS/Groupware and X-Cart to name a few.
## Summary
Whether you are using Smarty for a small website or massive enterprise
solution, it can accommodate your needs. There are numerous features
that make Smarty a great choice:
- separation of PHP from HTML/CSS just makes sense
- readability for organization and management
- security for 3rd party template access
- feature completeness, and easily extendable to your own needs
- massive user base, Smarty is here to stay
- LGPL license for commercial use
- 100% free to use, open source project
+352 -106
View File
@@ -1,56 +1,267 @@
What is Smarty?
==============
===============
## Requirements
Smarty can be run with PHP 7.1 to PHP 8.2.
Smarty is a template engine for PHP. More specifically, it facilitates a
manageable way to separate application logic and content from its
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.
## Installation
Smarty versions 3.1.11 or later can be installed with [Composer](https://getcomposer.org/).
For example, let\'s say you are creating a web page that is displaying a
newspaper article.
To get the latest stable version of Smarty use:
```bash
composer require smarty/smarty
````
- The article `$headline`, `$tagline`, `$author` and `$body` are
content elements, they contain no information about how they will be
presented. They are [passed](#api.assign) into Smarty by the
application.
To get the latest, unreleased version, use:
```bash
composer require smarty/smarty:dev-master
````
- Then the template designer edits the templates and uses a
combination of HTML tags and [template tags](#language.basic.syntax)
to format the presentation of these
[variables](#language.syntax.variables) with elements such as
tables, div\'s, background colors, font sizes, style sheets, svg
etc.
To get the previous stable version of Smarty, Smarty 3, use:
```bash
composer require smarty/smarty:^3
````
- One day the programmer needs to change the way the article content
is retrieved, ie a change in application logic. This change does not
affect the template designer, the content will still arrive in the
template exactly the same.
Here's how you create an instance of Smarty in your PHP scripts:
```php
<?php
- Likewise, if the template designer wants to completely redesign the
templates, this would require no change to the application logic.
require 'vendor/autoload.php';
$smarty = new Smarty();
```
- Therefore, the programmer can make changes to the application logic
without the need to restructure templates, and the template designer
can make changes to templates without breaking application logic.
Now that the library files are in place, it's time to setup the Smarty
directories for your application.
One design goal of Smarty is the separation of business logic and
presentation logic.
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.
- This means templates can certainly contain logic under the condition
that it is for presentation only. Things such as
[including](#language.function.include) other templates,
[alternating](#language.function.cycle) table row colors,
[upper-casing](#language.modifier.upper) a variable,
[looping](#language.function.foreach) over an array of data and
[displaying](#api.display) it are examples of presentation logic.
The defaults can be changed as follows:
```php
$smarty = new Smarty();
$smarty->setTemplateDir('/some/template/dir');
$smarty->setConfigDir('/some/config/dir');
$smarty->setCompileDir('/some/compile/dir');
$smarty->setCacheDir('/some/cache/dir');
```
- This does not mean however that Smarty forces a separation of
business and presentation logic. Smarty has no knowledge of which is
which, so placing business logic in the template is your own doing.
The compile dir and cache dir need to be writable for the user running the PHP script.
- Also, if you desire *no* logic in your templates you certainly can
do so by boiling the content down to text and variables only.
**Some of Smarty\'s features:**
- It is extremely fast.
- It is efficient since the PHP parser does the dirty work.
- No template parsing overhead, only compiles once.
- It is smart about [recompiling](#variable.compile.check) only the
template files that have changed.
- You can easily create your own custom
[functions](#language.custom.functions) and [variable
modifiers](#language.modifiers), so the template language is
extremely extensible.
- Configurable template [{delimiter}](#variable.left.delimiter) tag
syntax, so you can use `{$foo}`, `{{$foo}}`, `<!--{$foo}-->`, etc.
- The [`{if}..{elseif}..{else}..{/if}`](#language.function.if)
constructs are passed to the PHP parser, so the `{if...}` expression
syntax can be as simple or as complex an evaluation as you like.
- Allows unlimited nesting of
[`sections`](#language.function.section), `if's` etc.
- Built-in [caching](#caching) support
- Arbitrary [template](#resources) sources
- [Template Inheritance](#advanced.features.template.inheritance) for
easy management of template content.
- [Plugin](#plugins) architecture
Installation
============
Requirements {#installation.requirements}
============
Smarty requires a web server running PHP 5.2 or greater.
Basic Installation {#installing.smarty.basic}
==================
Install the Smarty library files which are in the `/libs/` sub directory
of the distribution. These are `.php` files that you SHOULD NOT edit.
They are shared among all applications and only get changed when you
upgrade to a new version of Smarty.
In the examples below the Smarty tarball has been unpacked to:
- `/usr/local/lib/Smarty-v.e.r/` for \*nix machines
- and `c:\webroot\libs\Smarty-v.e.r\` for the windows environment.
<!-- -->
Smarty-v.e.r/
libs/
Smarty.class.php
debug.tpl
sysplugins/* (everything)
plugins/* (everything)
Smarty uses a PHP [constant](&url.php-manual;define) named
[`SMARTY_DIR`](#constant.smarty.dir) which is the **full system file
path** to the Smarty `libs/` directory. Basically, if your application
can find the `Smarty.class.php` file, you do not need to set the
[`SMARTY_DIR`](#constant.smarty.dir) as Smarty will figure it out on its
own. Therefore, if `Smarty.class.php` is not in your
[include\_path](&url.php-manual;ini.core.php#ini.include-path), or you
do not supply an absolute path to it in your application, then you must
define `SMARTY_DIR` manually. `SMARTY_DIR` **must include a trailing
slash/**.
::: {.informalexample}
Here\'s how you create an instance of Smarty in your PHP scripts:
<?php
// NOTE: Smarty has a capital 'S'
require_once('Smarty.class.php');
$smarty = new Smarty();
?>
:::
Try running the above script. If you get an error saying the
`Smarty.class.php` file could not be found, you need to do one of the
following:
<?php
// *nix style (note capital 'S')
define('SMARTY_DIR', '/usr/local/lib/Smarty-v.e.r/libs/');
// windows style
define('SMARTY_DIR', 'c:/webroot/libs/Smarty-v.e.r/libs/');
// hack version example that works on both *nix and windows
// Smarty is assumend to be in 'includes/' dir under current script
define('SMARTY_DIR',str_replace("\\","/",getcwd()).'/includes/Smarty-v.e.r/libs/');
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();
?>
<?php
// *nix style (note capital 'S')
require_once('/usr/local/lib/Smarty-v.e.r/libs/Smarty.class.php');
// windows style
require_once('c:/webroot/libs/Smarty-v.e.r/libs/Smarty.class.php');
$smarty = new Smarty();
?>
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; *nix: "/path1:/path2"
include_path = ".:/usr/share/php:/usr/local/lib/Smarty-v.e.r/libs/"
; Windows: "\path1;\path2"
include_path = ".;c:\php\includes;c:\webroot\libs\Smarty-v.e.r\libs\"
<?php
// *nix
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'/usr/local/lib/Smarty-v.e.r/libs/');
// windows
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'c:/webroot/lib/Smarty-v.e.r/libs/');
?>
Now that the library files are in place, it\'s time to setup the Smarty
directories for your application:
- Smarty requires four directories which are by default named
`templates/`, `templates_c/`, `configs/` and `cache/`
- Each of these are definable by the Smarty class properties
[`$template_dir`](#variable.template.dir),
[`$compile_dir`](#variable.compile.dir),
[`$config_dir`](#variable.config.dir), and
[`$cache_dir`](#variable.cache.dir) respectively
- It is highly recommended that you setup a separate set of these
directories for each application that will use Smarty
- You can verify if your system has the correct access rights for
these directories with [`testInstall()`](#api.test.install).
For our installation example, we will be setting up the Smarty
environment for a guest book application. We picked an application only
for the purpose of a directory naming convention. You can use the same
environment for any application, just replace `guestbook/` with the name
of your application.
/usr/local/lib/Smarty-v.e.r/libs/
Smarty.class.php
debug.tpl
sysplugins/*
plugins/*
/web/www.example.com/
guestbook/
templates/
index.tpl
templates_c/
configs/
cache/
htdocs/
index.php
Be sure that you know the location of your web server\'s document root
as a file path. In the following examples, the document root is
`/web/www.example.com/guestbook/htdocs/`. The Smarty directories are
only accessed by the Smarty library and never accessed directly by the
web browser. Therefore to avoid any security concerns, it is recommended
(but not mandatory) to place these directories *outside* of the web
server\'s document root.
You will need as least one file under your document root, and that is
the script accessed by the web browser. We will name our script
`index.php`, and place it in a subdirectory under the document root
`/htdocs/`.
Smarty will need **write access** (windows users please ignore) to the
[`$compile_dir`](#variable.compile.dir) and
[`$cache_dir`](#variable.cache.dir) directories (`templates_c/` and
`cache/`), so be sure the web server user account can write to them.
> **Note**
>
@@ -59,62 +270,66 @@ The compile dir and cache dir need to be writable for the user running the PHP s
> can look in your `httpd.conf` file to see what user and group are
> being used.
```bash
chown nobody:nobody /web/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/
```
chown nobody:nobody /web/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
You can verify if your system has the correct access rights for
these directories with [`testInstall()`](./programmers/api-functions/api-test-install.md):
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/
```php
$smarty = new Smarty();
$smarty->setTemplateDir('/some/template/dir');
$smarty->setConfigDir('/some/config/dir');
$smarty->setCompileDir('/some/compile/dir');
$smarty->setCacheDir('/some/cache/dir');
$smarty->testInstall();
```
Now, let's create the `index.tpl` file that Smarty will display. This
needs to be located in the [`$template_dir`](./programmers/api-variables/variable-template-dir.md).
```html
{* Smarty *}
Hello {$name}, welcome to Smarty!
```
> **Note**
>
> `{* Smarty *}` is a template [comment](./designers/language-basic-syntax/language-syntax-comments.md). It
> `chmod 770` will be fairly tight security, it only allows user
> "nobody" and group "nobody" read/write access to the directories. If
> you would like to open up read access to anyone (mostly for your own
> convenience of viewing these files), you can use `775` instead.
We need to create the `index.tpl` file that Smarty will display. This
needs to be located in the [`$template_dir`](#variable.template.dir).
{* Smarty *}
Hello {$name}, welcome to Smarty!
> **Note**
>
> `{* Smarty *}` is a template [comment](#language.syntax.comments). It
> is not required, but it is good practice to start all your template
> files with this comment. It makes the file easy to recognize
> regardless of the file extension. For example, text editors could
> recognize the file and turn on special syntax highlighting.
Now lets edit our php file. We'll create an instance of Smarty,
[`assign()`](./programmers/api-functions/api-assign.md) a template variable and
[`display()`](./programmers/api-functions/api-display.md) the `index.tpl` file.
Now lets edit `index.php`. We\'ll create an instance of Smarty,
[`assign()`](#api.assign) a template variable and
[`display()`](#api.display) the `index.tpl` file.
```php
<?php
require 'vendor/autoload.php';
<?php
$smarty = new Smarty();
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty->setTemplateDir('/web/www.example.com/guestbook/templates/');
$smarty->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
$smarty->setCacheDir('/web/www.example.com/guestbook/cache/');
$smarty = new Smarty();
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
$smarty->setTemplateDir('/web/www.example.com/guestbook/templates/');
$smarty->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
$smarty->setCacheDir('/web/www.example.com/guestbook/cache/');
```
$smarty->assign('name','Ned');
//** un-comment the following line to show the debug console
//$smarty->debugging = true;
$smarty->display('index.tpl');
?>
> **Note**
>
@@ -125,47 +340,78 @@ $smarty->display('index.tpl');
> absolute paths. This ensures that Smarty is getting files from the
> directories you intended.
Now, run your PHP file. You should see *\"Hello Ned, welcome to Smarty!\"*
Now navigate to the `index.php` file with the web browser. You should
see *\"Hello Ned, welcome to Smarty!\"*
You have completed the basic setup for Smarty!
## Extended Setup {#installing.smarty.extended}
Extended Setup {#installing.smarty.extended}
==============
This is a continuation of the [basic
installation](#installing.smarty.basic), please read that first!
A slightly more flexible way to setup Smarty is to extend the Smarty
class and initialize your Smarty
A slightly more flexible way to setup Smarty is to [extend the
class](&url.php-manual;ref.classobj) and initialize your Smarty
environment. So instead of repeatedly setting directory paths, assigning
the same vars, etc., we can do that in one place.
```php
<?php
Lets create a new directory `/php/includes/guestbook/` and make a new
file called `setup.php`. In our example environment, `/php/includes` is
in our `include_path`. Be sure you set this up too, or use absolute file
paths.
use Smarty\Smarty;
class My_GuestBook extends Smarty {
<?php
public function __construct()
{
parent::__construct();
// load Smarty library
require('Smarty.class.php');
$this->setTemplateDir('/web/www.example.com/guestbook/templates/');
$this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$this->setConfigDir('/web/www.example.com/guestbook/configs/');
$this->setCacheDir('/web/www.example.com/guestbook/cache/');
// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
class Smarty_GuestBook extends Smarty {
}
```
function __construct()
{
Now, we can use `My_GuestBook` instead of `Smarty` in our scripts:
```php
$smarty = new My_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
```
// Class Constructor.
// These automatically get set with each new instance.
parent::__construct();
$this->setTemplateDir('/web/www.example.com/guestbook/templates/');
$this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$this->setConfigDir('/web/www.example.com/guestbook/configs/');
$this->setCacheDir('/web/www.example.com/guestbook/cache/');
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
}
?>
Now lets alter the `index.php` file to use `setup.php`:
<?php
require('guestbook/setup.php');
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
?>
Now you see it is quite simple to bring up an instance of Smarty, just
use `Smarty_GuestBook()` which automatically initializes everything for
our application.
+5 -27
View File
@@ -1,31 +1,12 @@
# Smarty 4 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
<h1>{$title|escape}</h1>
<p>
The number of pixels is: {math equation="x * y" x=$height y=$width}.
</p>
```
When this template is rendered, with the value "Hello world" for the variable $title, 640 for $width,
and 480 for $height, the result is:
```html
<h1>Hello world</h1>
<p>
The number of pixels is: 307200.
</p>
```
## Introduction
- [Philosophy](./philosophy.md) - or "Why do I need a template engine?"
- [Features](./features.md) - or "Why do I want Smarty?"
- [Preface](./preface.md)
- [Getting Started](./getting-started.md)
## Smarty for template designers
## Smarty for template developers
- [Basic Syntax](./designers/language-basic-syntax.md)
- [Variables](./designers/language-variables.md)
- [Variable Modifiers](./designers/language-modifiers.md)
@@ -37,13 +18,10 @@ and 480 for $height, the result is:
## 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
- [Some random tips & tricks](./appendixes/tips.md)
- [Troubleshooting](./appendixes/troubleshooting.md)
- [Extending Smarty With Plugins](./programmers/plugins.md)
-108
View File
@@ -1,108 +0,0 @@
Philosophy
=======
## What is Smarty?
Smarty is a template engine for PHP. More specifically, it facilitates a
manageable way to separate application logic and content from its
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
newspaper article.
- The article `$headline`, `$tagline`, `$author` and `$body` are
content elements, they contain no information about how they will be
presented. They are [passed](#api.assign) into Smarty by the
application.
- Then the template designer edits the templates and uses a
combination of HTML tags and [template tags](#language.basic.syntax)
to format the presentation of these
[variables](#language.syntax.variables) with elements such as
tables, div\'s, background colors, font sizes, style sheets, svg
etc.
- One day the programmer needs to change the way the article content
is retrieved, ie a change in application logic. This change does not
affect the template designer, the content will still arrive in the
template exactly the same.
- Likewise, if the template designer wants to completely redesign the
templates, this would require no change to the application logic.
- Therefore, the programmer can make changes to the application logic
without the need to restructure templates, and the template designer
can make changes to templates without breaking application logic.
## Goals
The Smarty design was largely driven by these goals:
- clean separation of presentation from application code
- PHP backend, Smarty template frontend
- complement PHP, not replace it
- fast development/deployment for programmers and designers
- quick and easy to maintain
- syntax easy to understand, no PHP knowledge necessary
- flexibility for custom development
- security: insulation from PHP
- free, open source
## Two camps of thought
When it comes to templating in PHP, there are basically two camps of
thought. The first camp exclaims that \"PHP is a template engine\". This
approach simply mixes PHP code with HTML. Although this approach is
fastest from a pure script-execution point of view, many would argue
that the PHP syntax is messy and complicated when mixed with tagged
markup such as HTML.
The second camp exclaims that presentation should be void of all
programming code, and instead use simple tags to indicate where
application content is revealed. This approach is common with other
template engines (even in other programming languages), and is also the
approach that Smarty takes. The idea is to keep the templates focused
squarely on presentation, void of application code, and with as little
overhead as possible.
## Why is separating PHP from templates important?
Two major benefits:
- SYNTAX: Templates typically consist of semantic markup such as HTML.
PHP syntax works well for application code, but quickly degenerates
when mixed with HTML. Smarty\'s simple {tag} syntax is designed
specifically to express presentation. Smarty focuses your templates
on presentation and less on \"code\". This lends to quicker template
deployment and easier maintenance. Smarty syntax requires no working
knowledge of PHP, and is intuitive for programmers and
non-programmers alike.
- INSULATION: When PHP is mixed with templates, there are no
restrictions on what type of logic can be injected into a template.
Smarty insulates the templates from PHP, creating a controlled
separation of presentation from business logic. Smarty also has
security features that can further enforce restrictions on
templates.
## Web designers and PHP
A common question: "Web designers have to learn a syntax anyway, why
not PHP?" Of course web designers can learn PHP, and they may already
be familiar with it. The issue isn't their ability to learn PHP, it is
about the consequences of mixing PHP with HTML. If designers use PHP, it
is too easy to add code into templates that doesn't belong there (you
just handed them a swiss-army knife when they just needed a knife.) You
can teach them the rules of application design, but this is probably
something they don't really need to learn (now they are developers!)
The PHP manual is also an overwhelming pile of information to sift
through. It is like handing the owner of a car the factory assembly
manual when all they need is the owners manual. Smarty gives web
designers exactly the tools they need, and gives developers fine-grained
control over those tools. The simplicity of the tag-based syntax is also
a huge welcome for designers, it helps them streamline the organization
and management of templates.
+212
View File
@@ -0,0 +1,212 @@
Preface
=======
**The Philosophy**
The Smarty design was largely driven by these goals:
- clean separation of presentation from application code
- PHP backend, Smarty template frontend
- complement PHP, not replace it
- fast development/deployment for programmers and designers
- quick and easy to maintain
- syntax easy to understand, no PHP knowledge necessary
- flexibility for custom development
- security: insulation from PHP
- free, open source
**What is Smarty?**
Smarty is a template engine for PHP, facilitating the separation of
presentation (HTML/CSS) from application logic. This implies that *PHP
code is application logic*, and is separated from the presentation.
**Two camps of thought**
When it comes to templating in PHP, there are basically two camps of
thought. The first camp exclaims that \"PHP is a template engine\". This
approach simply mixes PHP code with HTML. Although this approach is
fastest from a pure script-execution point of view, many would argue
that the PHP syntax is messy and complicated when mixed with tagged
markup such as HTML.
The second camp exclaims that presentation should be void of all
programming code, and instead use simple tags to indicate where
application content is revealed. This approach is common with other
template engines (even in other programming languages), and is also the
approach that Smarty takes. The idea is to keep the templates focused
squarely on presentation, void of application code, and with as little
overhead as possible.
**Why is separating PHP from templates important?**
Two major benefits:
- SYNTAX: Templates typically consist of semantic markup such as HTML.
PHP syntax works well for application code, but quickly degenerates
when mixed with HTML. Smarty\'s simple {tag} syntax is designed
specifically to express presentation. Smarty focuses your templates
on presentation and less on \"code\". This lends to quicker template
deployment and easier maintenance. Smarty syntax requires no working
knowledge of PHP, and is intuitive for programmers and
non-programmers alike.
- INSULATION: When PHP is mixed with templates, there are no
restrictions on what type of logic can be injected into a template.
Smarty insulates the templates from PHP, creating a controlled
separation of presentation from business logic. Smarty also has
security features that can further enforce restrictions on
templates.
**Web designers and PHP**
A common question: \"Web designers have to learn a syntax anyways, why
not PHP?\" Of course web designers can learn PHP, and they may already
be familiar with it. The issue isn\'t their ability to learn PHP, it is
about the consequences of mixing PHP with HTML. If designers use PHP, it
is too easy to add code into templates that doesn\'t belong there (you
just handed them a swiss-army knife when they just needed a knife.) You
can teach them the rules of application design, but this is probably
something they don\'t really need to learn (now they are developers!)
The PHP manual is also an overwhelming pile of information to sift
through. It is like handing the owner of a car the factory assembly
manual when all they need is the owners manual. Smarty gives web
designers exactly the tools they need, and gives developers fine-grained
control over those tools. The simplicity of the tag-based syntax is also
a huge welcome for designers, it helps them streamline the organization
and management of templates.
**Implementation is Important**
Although Smarty gives you the tools to make a clean separation of
presentation from application code, it also gives you plenty of room to
bend those rules. A poor implementation (i.e. injecting PHP in
templates) will cause more problems than the presentation separation was
meant to resolve. The documentation does a good job of indicating what
things to watch out for. Also see the Best Practices section of the
Smarty website.
**How does it work?**
Under the hood, Smarty \"compiles\" (basically copies and converts) the
templates into PHP scripts. This happens once when each template is
first invoked, and then the compiled versions are used from that point
forward. Smarty takes care of this for you, so the template designer
just edits the Smarty templates and never has to manage the compiled
versions. This approach keeps the templates easy to maintain, and yet
keeps execution times extremely fast since the compiled code is just
PHP. And of course, all PHP scripts take advantage of PHP op-code caches
such as APC.
**Template Inheritance**
Template inheritance is new to Smarty 3, and it\'s one of many great new
features. Before template inheritance, we managed our templates in
pieces such as header and footer templates. This organization lends
itself to many problems that require some hoop-jumping, such as managing
content within the header/footer on a per-page basis. With template
inheritance, instead of including other templates we maintain our
templates as single pages. We can then manipulate blocks of content
within by inheriting them. This makes templates intuitive, efficient and
easy to manage. See the Template Inheritance section of th Smarty
website for more info.
**Why not use XML/XSLT syntax?**
There are a couple of good reasons. First, Smarty can be used for more
than just XML/HTML based templates, such as generating emails,
javascript, CSV, and PDF documents. Second, XML/XSLT syntax is even more
verbose and fragile than PHP code! It is perfect for computers, but
horrible for humans. Smarty is about being easy to read, understand and
maintain.
**Template Security**
Although Smarty insulates you from PHP, you still have the option to use
it in certain ways if you wish. Template security forces the restriction
of PHP (and select Smarty functions.) This is useful if you have third
parties editing templates, and you don\'t want to unleash the full power
of PHP or Smarty to them.
**Integration**
Sometimes Smarty gets compared to Model-View-Controller (MVC)
frameworks. Smarty is not an MVC, it is just the presentation layer,
much like the View (V) part of an MVC. As a matter of fact, Smarty can
easily be integrated as the view layer of an MVC. Many of the more
popular ones have integration instructions for Smarty, or you may find
some help here in the forums and documentation.
**Other Template Engines**
Smarty is not the only engine following the *\"Separate Programming Code
from Presentation\"* philosophy. For instance, Python has template
engines built around the same principles such as Django Templates and
CheetahTemplate. *Note: Languages such as Python do not mix with HTML
natively, which give them the advantage of proper programming code
separation from the outset. There are libraries available to mix Python
with HTML, but they are typically avoided.*
**What Smarty is Not**
Smarty is not an application development framework. Smarty is not an
MVC. Smarty is not an alternative to Zend Framework, CodeIgniter,
PHPCake, or any of the other application development frameworks for PHP.
Smarty is a template engine, and works as the (V)iew component of your
application. Smarty can easily be coupled to any of the engines listed
above as the view component. No different than any other software,
Smarty has a learning curve. Smarty does not guarantee good application
design or proper separation of presentation, this still needs to be
addressed by a competent developer and web designer.
**Is Smarty Right for Me?**
Smarty is not meant to be a tool for every job. The important thing is
to identify if Smarty fits your needs. There are some important
questions to ask yourself:
TEMPLATE SYNTAX. Are you content with PHP tags mixed with HTML? Are your
web designers comfortable with PHP? Would your web designers prefer a
tag-based syntax designed for presentation? Some experience working with
both Smarty and PHP helps answer these questions.
THE BUSINESS CASE: Is there a requirement to insulate the templates from
PHP? Do you have untrusted parties editing templates that you do not
wish to unleash the power of PHP to? Do you need to programmatically
control what is and is not available within the templates? Smarty
supplies these capabilities by design.
FEATURE SET: Does Smarty\'s features such as caching, template
inheritance and plugin architecture save development cycles writing code
that would be needed otherwise? Does the codebase or framework you plan
on using have the features you need for the presentation component?
Templating in PHP is a hot topic, and opinions widely vary. It is
important that you understand Smarty, understand your own requirements,
and make an informed decision for yourself. You are welcome to ask
specific questions in the forums or the IRC channel.
See also the section about \"Use Cases and Work Flow\" on the Smarty
website.
**Sites using Smarty**
There are tens of thousands of unique visitors on the Smarty website
daily, mostly developers reading documentation. Many well-known PHP
projects make use of Smarty such as XOOPS CMS, CMS Made Simple, Tiki
CMS/Groupware and X-Cart to name a few.
**Summary**
Whether you are using Smarty for a small website or massive enterprise
solution, it can accommodate your needs. There are numerous features
that make Smarty a great choice:
- separation of PHP from HTML/CSS just makes sense
- readability for organization and management
- security for 3rd party template access
- feature completeness, and easily extendable to your own needs
- massive user base, Smarty is here to stay
- LGPL license for commercial use
- 100% free to use, open source project
@@ -29,7 +29,7 @@ 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,
(beginningwith \'\_\'). 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
@@ -10,14 +10,15 @@ 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. Smarty will
[`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\Template\ $template)
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}))!',
@@ -37,5 +38,6 @@ to return the result of the processing.
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).
@@ -5,14 +5,15 @@ 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. Smarty will
[`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\Template\ $template)
function add_header_comment($tpl_source, Smarty_Internal_Template $template)
{
return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source;
}
@@ -8,7 +8,8 @@ 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.
[`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.
@@ -18,7 +19,7 @@ This will remove all the html comments in the template source.
<?php
// put this in your application
function remove_dw_comments($tpl_source, \Smarty\Template\ $template)
function remove_dw_comments($tpl_source, Smarty_Internal_Template $template)
{
return preg_replace("/<!--#.*-->/U",'',$tpl_source);
}
@@ -2,17 +2,39 @@ 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
the templates eg 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:
- `$php_handling` determines how Smarty to handle PHP code embedded in
templates. Possible values are:
- Smarty::PHP\_PASSTHRU -\> echo PHP tags as they are
- Smarty::PHP\_QUOTE -\> escape tags as entities
- Smarty::PHP\_REMOVE -\> remove php tags
- Smarty::PHP\_ALLOW -\> execute php tags
The default value is Smarty::PHP\_PASSTHRU.
If security is enabled the [`$php_handling`](#variable.php.handling)
setting of the Smarty object is not checked for security.
- `$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_uri` is an array of regular expressions matching URIs that
concidered 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
[`{include_php}`](#language.function.include.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
@@ -21,7 +43,7 @@ instance of the Smarty\_Security class. These are the possible settings:
like authentication-tokens).
The expression `'#https?://.*smarty.net$#i'` would allow accessing
the following URIs:
the follwing URIs:
- `http://smarty.net/foo`
@@ -47,6 +69,19 @@ instance of the Smarty\_Security class. These are the possible settings:
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
@@ -75,8 +110,12 @@ instance of the Smarty\_Security class. These are the possible settings:
super globals can be accessed by the template. The default is
\"true\".
- `$allow_php_tag` is a boolean flag which controls if {php} and
{include\_php} tags can be used by the template. The default is
\"false\".
If security is enabled, no private methods, functions or properties of
static classes or assigned objects can be accessed (beginning with
static classes or assigned objects can be accessed (beginningwith
\'\_\') by the template.
To customize the security policy settings you can extend the
@@ -84,9 +123,15 @@ Smarty\_Security class or create an instance of it.
<?php
require 'Smarty.class.php';
class My_Security_Policy extends \Smarty\Security {
public $allow_constants = false;
class My_Security_Policy extends Smarty_Security {
// disable all PHP functions
public $php_functions = null;
// remove PHP tags
public $php_handling = Smarty::PHP_REMOVE;
// allow everthing as modifier
public $php_modifiers = array();
}
$smarty = new Smarty();
// enable security
@@ -95,9 +140,15 @@ Smarty\_Security class or create an instance of it.
<?php
require 'Smarty.class.php';
$smarty = new Smarty();
$my_security_policy = new \Smarty\Security($smarty);
$my_security_policy->allow_constants = false;
$my_security_policy = new Smarty_Security($smarty);
// disable all PHP functions
$my_security_policy->php_functions = null;
// remove PHP tags
$my_security_policy->php_handling = Smarty::PHP_REMOVE;
// allow everthing as modifier
$my_security_policy->php_modifiers = array();
// enable security
$smarty->enableSecurity($my_security_policy);
?>
@@ -113,5 +164,5 @@ Smarty\_Security class or create an instance of it.
> **Note**
>
> Most security policy settings are only checked when the template gets
> compiled. For that reason you should delete all cached and compiled
> compiled. For that reasion you should delete all cached and compiled
> template files when you change your security settings.
@@ -33,7 +33,7 @@ can override all or some of the parent named block areas.
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.
type. The later provides even more flexibillity.
> **Note**
>
@@ -8,7 +8,7 @@ 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
called by induvidual template objects. Modification done to a template
object will apply only for that template and its included subtemplates.
+2
View File
@@ -31,6 +31,7 @@ Smarty Class Methods {#api.functions}
- [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
@@ -54,6 +55,7 @@ Smarty Class Methods {#api.functions}
- [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**
>
@@ -26,7 +26,7 @@ the following parameters:
variables assigned to any of the objects in it\'s parent chain.
Data objects are used to create scopes for assigned variables. They can
be used to control which variables are seen by which templates.
be used to have controll which variables are seen by which templates.
<?php
@@ -9,7 +9,7 @@ string
disableSecurity
This disables security checking on templates.
This disables securty checking on templates.
See also [`enableSecurity()`](#api.enable.security), and
[Security](#advanced.features.security).
@@ -31,9 +31,7 @@ PARAMETER.COMPILEID
<?php
use Smarty\Smarty;
include(SMARTY_DIR.'Smarty.class.php');
$smarty = new Smarty();
$smarty->setCaching(true);
@@ -25,7 +25,7 @@ string
enableSecurity
This enables security checking on templates. It uses the following
This enables securty checking on templates. It uses the following
parameters:
- `securityclass` is an optional parameter. It\'s the name of the
@@ -0,0 +1,40 @@
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);
?>
@@ -22,8 +22,8 @@ string
compile\_id
- This only works if [`$caching`](#variable.caching) is set to one of
`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or
`\Smarty\Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching
`Smarty::CACHING_LIFETIME_CURRENT` or
`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
@@ -18,7 +18,7 @@ string
name
The first argument specifies the type of the filter to load and can be
one of the following: `variable`, `pre`, `post` or `output`. The second argument
one of the following: `pre`, `post` or `output`. The second argument
specifies the `name` of the filter plugin.
@@ -37,5 +37,6 @@ specifies the `name` of the filter plugin.
See also [`registerFilter()`](#api.register.filter) and [advanced
See also [`registerFilter()`](#api.register.filter),
[`$autoload_filters`](#variable.autoload.filters) and [advanced
features](#advanced.features).
@@ -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\Smarty::unmuteExpectedErrors()` removes the current error handler.
Please note, that if you\'ve registered any custom error handlers after
`Smarty::unmuteExpectedErrors()` removes the current error handler.
Please note, that if you\'ve registerd any custom error handlers after
the muteExpectedErrors() call, the unmute will not remove Smarty\'s
muting error handler, but the one registered last.
@@ -31,7 +31,7 @@ how to create custom CacheResources.
<?php
$smarty->registerCacheResource('mysql', new My_CacheResource_Mysql());
$smarty->registerCacheResource('mysql', new Smarty_CacheResource_Mysql());
?>
@@ -18,7 +18,7 @@ not find a definition for a tag otherwise. It uses the following
parameters:
If during compilation Smarty encounters tag which is not defined
internal, registered or located in the plugins folder it tries to
internal, registered or loacted in the plugins folder it tries to
resolve it by calling the registered default plugin handler. The handler
may be called several times for same undefined tag looping over valid
plugin types.
@@ -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\Template\ $template template object
* @param Smarty_Internal_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)
@@ -38,7 +38,8 @@ 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), [template pre
[`loadFilter()`](#api.load.filter),
[`$autoload_filters`](#variable.autoload.filters), [template pre
filters](#advanced.features.prefilters) [template post
filters](#advanced.features.postfilters) [template output
filters](#advanced.features.outputfilters) section.
@@ -32,9 +32,9 @@ cache\_attrs
This method registers functions or methods defined in your script as
plugin. It uses the following parameters:
- `cacheable` can be omitted in most cases. See
- `cacheable` and `cache_attrs` can be omitted in most cases. See
[controlling cacheability of plugins output](#caching.cacheable) on
how to use this properly.
how to use them properly.
<!-- -->
@@ -37,7 +37,7 @@ information on how to setup a function for fetching templates.
<?php
$smarty->registerResource('mysql', new My_Resource_Mysql());
$smarty->registerResource('mysql', new Smarty_Resource_Mysql());
?>
@@ -55,4 +55,5 @@ And the php script
See also [`display()`](#api.display), [`fetch()`](#api.fetch),
and [`{include}`](#language.function.include)
[`{include}`](#language.function.include) and
[`{insert}`](#language.function.insert)
@@ -10,7 +10,7 @@ void
testInstall
This function verifies that all required working folders of the Smarty
installation can be accessed. It does output a corresponding protocol.
installation can be accessed. It does output a corresponding protocoll.
<?php
+7
View File
@@ -4,7 +4,9 @@ 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)
@@ -29,6 +31,7 @@ them directly, or use the corresponding setter/getter methods.
- [$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)
@@ -36,9 +39,13 @@ them directly, or use the corresponding setter/getter methods.
- [$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)
- [$php_handling](./api-variables/variable-php-handling.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**
@@ -0,0 +1,18 @@
\$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.
@@ -0,0 +1,21 @@
\$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)
@@ -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\Smarty::CACHING\_LIFETIME\_CURRENT or
\Smarty\Smarty::CACHING\_LIFETIME\_SAVED) for `$cache_lifetime` to have any
Smarty::CACHING\_LIFETIME\_CURRENT or
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\Smarty::CACHING\_OFF).
[`$caching`](#variable.caching) = Smarty::CACHING\_OFF).
- If you want to give certain templates their own cache lifetime, you
could do this by setting [`$caching`](#variable.caching) =
\Smarty\Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a
Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a
unique value just before calling [`display()`](#api.display) or
[`fetch()`](#api.fetch).
@@ -4,7 +4,8 @@
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.
the content. This works only on cached content without
[`{insert}`](#language.function.insert) tags.
See also [`$caching`](#variable.caching),
[`$cache_lifetime`](#variable.cache.lifetime), and the [caching
@@ -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\Smarty::CACHING\_OFF. If your templates consistently generate
constant 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\Smarty::CACHING\_LIFETIME\_CURRENT or
\Smarty\Smarty ::CACHING\_LIFETIME\_SAVED enables caching.
- A constant value of Smarty::CACHING\_LIFETIME\_CURRENT or
Smarty::CACHING\_LIFETIME\_SAVED enables caching.
- A value of \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT tells Smarty to use
- A value of 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\Smarty::CACHING\_LIFETIME\_SAVED tells Smarty to use the
- A value of 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
@@ -18,7 +18,7 @@ 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\Smarty::COMPILECHECK_CACHEMISS`. This enables Smarty to revalidate the
`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.
@@ -1,7 +1,7 @@
\$compile\_id {#variable.compile.id}
=============
Persistent compile identifier. As an alternative to passing the same
Persistant compile identifier. As an alternative to passing the same
`$compile_id` to each and every function call, you can set this
`$compile_id` and it will be used implicitly thereafter.
@@ -10,7 +10,7 @@ post-filters](#plugins.prefilters.postfilters) you must use a unique
`$compile_id` to keep the compiled template files separated.
For example a [prefilter](#plugins.prefilters.postfilters) that
localizes your templates (that is: translates language dependent parts)
localizes your templates (that is: translates language dependend parts)
at compile time, then you could use the current language as
`$compile_id` and you will get a set of compiled templates for each
language you use.
@@ -2,7 +2,8 @@
============
This is the name of the template file used for the debugging console. By
default, it is named `debug.tpl` and is located in `src/debug.tpl`.
default, it is named `debug.tpl` and is located in the
[`SMARTY_DIR`](#constant.smarty.dir).
See also [`$debugging`](#variable.debugging) and the [debugging
console](#chapter.debugging.console) section.
@@ -8,7 +8,7 @@ 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 \Smarty\Exception is thrown.
> case a SmartyException is thrown.
<?php
@@ -8,7 +8,7 @@ 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 \Smarty\Exception is thrown.
> case a SmartyException is thrown.
<?php
@@ -0,0 +1,13 @@
\$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.
@@ -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\Smarty::muteExpectedErrors();` after setting up custom error handling
`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()`
@@ -3,7 +3,7 @@
Setting `$escape_html` to TRUE will escape all template variable output
by wrapping it in
`htmlspecialchars({$output}, ENT_QUOTES, $char_set);`,
`htmlspecialchars({$output}, ENT_QUOTES, SMARTY_RESOURCE_CHAR_SET);`,
which is the same as `{$variable|escape:"html"}`.
Template designers can choose to selectively disable this feature by
@@ -2,6 +2,6 @@
==================
This is maximum time in seconds a cache lock is valid to avoid dead
locks. The default value is 10 seconds.
locks. The deafult value is 10 seconds.
See also [`$cache_locking`](#variable.cache.locking)
@@ -0,0 +1,21 @@
\$php\_handling {#variable.php.handling}
===============
This tells Smarty how to handle PHP code embedded in the templates.
There are four possible settings, the default being
`Smarty::PHP_PASSTHRU`. Note that this does NOT affect php code within
[`{php}{/php}`](#language.function.php) tags in the template.
- `Smarty::PHP_PASSTHRU` - Smarty echos tags as-is.
- `Smarty::PHP_QUOTE` - Smarty quotes the tags as html entities.
- `Smarty::PHP_REMOVE` - Smarty removes the tags from the templates.
- `Smarty::PHP_ALLOW` - Smarty will execute the tags as PHP code.
> **Note**
>
> Embedding PHP code into templates is highly discouraged. Use [custom
> functions](#plugins.functions) or [modifiers](#plugins.modifiers)
> instead.
@@ -0,0 +1,28 @@
\$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).
@@ -15,12 +15,22 @@ found.
> document root.
> **Note**
>
> If the directories known to `$template_dir` are relative to
> directories known to the
> [include\_path](&url.php-manual;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).
@@ -0,0 +1,8 @@
\$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
[`{include_php}`](#language.function.include.php).
@@ -0,0 +1,49 @@
\$use\_include\_path {#variable.use.include.path}
====================
This tells smarty to respect the
[include\_path](&url.php-manual;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](&url.php-manual;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](&url.php-manual;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)
@@ -10,7 +10,7 @@ environments do not allow PHP processes to create directories, so this
must be disabled which is the default.
Sub directories are more efficient, so use them if you can.
Theoretically you get much better performance on a filesystem with 10
Theoretically you get much better perfomance on a filesystem with 10
directories each having 100 files, than with 1 directory having 1000
files. This was certainly the case with Solaris 7 (UFS)\... with newer
filesystems such as ext3 and especially reiserfs, the difference is
+50 -2
View File
@@ -76,14 +76,62 @@ third parameter to [`registerPlugin()`](#api.register.plugin) is called
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 affect the compiled template code. If you
> 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.
Example `index.php`:
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);
+8 -8
View File
@@ -17,11 +17,11 @@ 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,
`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\"
`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
@@ -63,10 +63,10 @@ to invoke your custom CacheResource implementation.
* INDEX(`modified`)
* ) ENGINE = InnoDB;</pre>
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class My_CacheResource_Mysql extends \Smarty\Cacheresource\Custom {
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
// PDO instance
protected $db;
protected $fetch;
@@ -77,7 +77,7 @@ to invoke your custom CacheResource implementation.
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
throw new \Smarty\Exception('Mysql Resource failed: ' . $e->getMessage());
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');
@@ -211,10 +211,10 @@ to invoke your custom CacheResource implementation.
* 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 My_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore {
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
/**
* memcache instance
* @var Memcache
+2 -2
View File
@@ -25,10 +25,10 @@ like.
- 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.
single cache group heirarchy 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
heirarchy, 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

Some files were not shown because too many files have changed in this diff Show More