mirror of
https://github.com/smarty-php/smarty.git
synced 2025-06-24 22:41:36 +02:00
Smarty5 (#852)
* WIP converting code to PSR-4 * More PSR4 rewriting * Removed autoload filters * WIP making compile classes PSR-4 * WIP making compile classes PSR-4 * Replace Smarty:: with symfony/polyfill-mbstring * WIP making compile classes PSR-4 * finished rewriting all compile classes into PSR-4 * Rewrote all Compile and Compiler classes to PSR-4 * WIP rewriting smarty_internal_method_* * Finished moving smarty_internal_method_* * smarty_internal_resource_* to PSR-4 * Refactored all _runtime_* by merging them into the proper classes or by transforming them into Runtime Extensions. * src/Template/* to PSR-4 * src/sysplugins/* to PSR-4 * Entire src dir now PSR-4 compatible * Add makefile, PSR-4 ModifierCompilers * Rewrote all default modifiers and functions from the plugins folder to PSR-4 classes * Rewrote remaining plugins to PSR-4, plugins dir is now gone. * WIP moving Smarty to PSR-4. * fixed pre/post/output filters and removed some old todo-comments * filter tests passing * Fixed TemplateObject test * Fix CustomResourceAmbiguousTest * Fixed CacheResource implementation and tests * Fixed setfilter * Fixed DefaultPluginHandlerTest for function plugins (blocks still break) * move runPluginFromDefaultHandler to new Runtime class * Introduce formatParamsArray method for recurring code fragment * Fix code duplication in block compilers and fix (most) BlockPluginTests. Default plugin handler blocks still need fixing. * minor fixes * Implemented the DefaultHandlerBlockCompiler, made the dependencies of the template compiler into properties, fixed a couple of unit tests * Removed support for PHP include path, and removed the ::loadPlugin method. * Removed now unneeded PHPunit annotations @run(Tests)InSeparateProcess, @preserveGlobalState and @backupStaticAttributes. Made CacheResourceTestCommon abstract to prevent the base class from running tests (and always failing). Unregister a previously registered stream wrapper. Fixes a lot of tests. * Fix scoping / global state problems in tests by using DI in Default Extension. Also removing a bunch of old fashioned phpdoc annotations that are superseded by namespaces. * Make DefaultExtension lazy load again. * Removed deprecated extends_recursion property and fix bug in CodeFrame compiler due to use of clone. * Fixed BC loading of resource pluging from dir and all ResourcePluginTest tests * Removed PHP functions and checks for the already removed php modifiers. Re-implemented functions as regular functions. Probably should compile these directly. * Fixed stream resources * 2 small fixes for unit tests * Fixed modifiercompiler handling multiple/chained modifiers * Rewrote global static global_tpl_vars to getters/setters on Smarty class, fixing several test cases. Added a ::getValue() method to Variable. * Fixed issue related to scoping of left/right delimiter overrides * Added strlen function, fixing some unit tests * Fix bug in calling BC function handlers. * WIP replacing direct access tpl_vars with proper getter/setters. * WIP * WIP rewriting variable scopes * WIP fixing the complicated variables scopes architecture. Right now more tests are failing than before... :( * Fixed minor unit tests * Made variable scoping more sensible * Fix configfile tests * removed phpplugin, removed now unused uncompiled handler and all checks for this, fixed a refactorbug in InheritanceRuntime. Moved getRenderedTemplateCode method to Smarty\Template. Renamed Cache en Compiled base class to GeneratedPhpFile for more clarity and distinction from Resource classes. Inlined Cached::create into its only caller. Some other minor improvements. Removed php7.1 CI tests. * Removed the allowUndefinedVars check from the smarty error handlers, because undefined vars no longer throw an error, unless smarty->error_unassigned is set to true. * Replace direct access to inheritance property on Template object by proper getter. * converted 3 public properties on Template into getters/setters. unified Template creation code. Provided a getter/setter for the has_nocache_code property. Removed the useless DataObject class. Fixed a few tests. Removed the variable-allow-php-templates property from the docs. * Simplified the (no)caching architecture by: - removing support for $cache_attrs for registered plugins, - removing the undocumented {make_nocache} tag and the deprecated {insert} tag and associated code - removing support for a compile_id property on include tags. Fixes a bug in extends: resources by propagating the nocache-hashes between a master template and it's subtemplates in \Smarty\Template::_subTemplateRender. This might need further improvement. * Removed unneeded magic setters/getters/destructors and the like. * Replaced a bunch of direct property access with getters/setters. * Update test runners: no longer support PHP7.1, add PHP8.2 * Fixed scope in variable assignments in included and extended templates, fixed dependencies for testing freshness of caches. Added some unit tests and fixed a class reference to pass some more tests. * Fix searchParents parameter, fixing GetTemplateVarsTest * @var integer > @var int for vsCode * Fix function caching function name * Fixed cacheability of block plugins. * Moved handling of smarty.block.* to special compilers, because they aren't real tags. Organized tag-stack handling in compiler, unified nocache handling in compiler. * Fixed block append/prepend functionality * Fix testRegisterCompilerFunction by parsing argument correctly. * Made exception msgs exactly the same again, fixing some unit tests * Fix default plugin handler * Simply the "isFresh" method by not including the first param anymore. Fix a couple of unit tests by respecting tag_nocache set by nocache vars used in a tag. * Removed the undocumented {block_parent} and {parent} alternatives to {$smarty.block.parent} and {block_child} and {child} alternatives to {$smarty.block.child} * Fix inhertiance implementation for $smarty.block.child * Fixed all inheritance issues * Handle BC registered compilers and missed parameters for openTag and closeTag. * Fix all foreach unit tests * Fixed the {if} failures. * Fix major {include} bug * Fixed bug in {include} variable assignment and removed some unused/unrequired code * Fix function call compilation using {functionname} syntax for in-template defined functions. * Drop a unit tests bc we no longer support direct access to PHP-functinos such as sin() * Fixed all scope assignment bugs * Convert isset and empty to modifiercomilers, and smooth the error handling to fix unit tests. * Fixed getCachedContent * Add TODO list * Run composer install before online test run * Attempt to fix CI * revise CI/CD workflows, bypass packagist for lexer * Update ci.yml * Update ci.yml * fixes in source files * Update ci.yml * Update ci.yml * attempt to load smarty-lexer directly from zip file * Shouldnt need Github token now * correct type of repository * Updated the changelog * Re-organized rendering (read source / compile / cache) process to avoid circular dependencies. Deactivated merge_compiled_includes and the {include inline} attribute. They don't seem to do much in terms of performance, but we'll have to check back. * updated todo * Fix smarty-lexer dependency for the time being * Fix smarty-lexer dependency for the time being (remove direct ref to github) * Pushed Lexers/Parsers into VCS again in order to be able to deliver using Packagist/Composer * Re-organized rendering (read source / compile / cache) process to avoid circular dependencies. * Run make regardless of timestamps, so we are sure unit tests run with the generated PHP code, not with accidental human made changes to Lexer/Parser. * Update composer packages cache key Update composer packages cache key to trigger refresh on lexer * 4.0.2 of smarty-lexer is released, use that * Throw compile error when using a modifier where it won't work. Fixes #526. * verify that native PHP functions cannot be used as a modifier and verify that an easy userland workaround exists. Fixes #813. * Add test for registering compiler plugin with positional params. Fixes #164 * move test methods because some other test methods rely on their relative positions * Smarty no longer calls `mb_internal_encoding()` and doesn't check for deprecated `mbstring.func_overload` ini directive. Fixes #480. * Generated `<script>` tags lo longer have deprecated `type="text/javascript"` or `language="Javascript"` attributes. Fixes #815. * Fix error in docs on prepend/append. Fixes #818. * Move all creating of templates to Smarty::createTemplate, adding a private property containing previously generated templates for speed. * Load compiled object in template constructor so it will be cached. * WIP for performance improvements. Removed $smarty->_current_file and $smarty->allow_ambiguous_resources properties, both unused. Removed public Source::filepath property. Cached an Compiled files (and Exceptions) no longer rely on the filepath being set. Removed explicit tests for cached and compiled filenames. The exact implementation is not important. Added tests for compile_check property, fixing a file_exists check that would always be done on source template files, even when compile_check was true. Remove code duplication between Source en Config classes. Added a local $_smarty_current_dir to the generated code files for backwards compatability for {$smarty.current_dir}. * remove additional calls to getCached() * updated todo * Add mkdocs for docs * add missing folder for unit tests * Revert latest CI changes, we'll update docs by hand for now * multiversion mkdocs config * fixes to docs * WIP improving the docs * Improved another chunk of the designers docs * Finished improving designers docs * Update code examples to use Smarty\Smarty and autoload instead of require_once calls and new Smarty * Further WIP improving docs * Updated changelog and todo list * WIP on API docs * WIP docs (added page on config) * Fixed markdown syntax. Fixes #879 * Added full support and documentation for ternary operator. Fixes #881 * updated changelog * fixed error in the mkdocs TOC * Added support for null coalescing operator Fixes #882 * Add docs for null coalescing * more docs * Improved docs on compile checking and inheritance * Rewrote docs on filters and resources. * Add makefile entries for generating docs * Docs on caching * finished docs on security and extending smarty * Added Smarty::setExtensions(), fixed unit test for the null coalescing operator. Updated docs about registering a custom extension. * updated todos * fix template invalidation when migrating to 5.0
This commit is contained in:
16
.github/workflows/ci.yml
vendored
16
.github/workflows/ci.yml
vendored
@ -25,7 +25,6 @@ jobs:
|
||||
- ubuntu-latest
|
||||
|
||||
php-version:
|
||||
- "7.1"
|
||||
- "7.2"
|
||||
- "7.3"
|
||||
- "7.4"
|
||||
@ -63,17 +62,20 @@ 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
|
||||
with:
|
||||
path: vendor
|
||||
key: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
|
||||
key: v5r2-${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-php-${{ matrix.php-version }}-
|
||||
v5r1-${{ runner.os }}-php-${{ matrix.php-version }}-
|
||||
|
||||
- name: Install dependencies
|
||||
uses: php-actions/composer@v6
|
||||
|
||||
- name: Run make
|
||||
run: make -B
|
||||
|
||||
- name: Run tests with phpunit
|
||||
run: ./run-tests.sh
|
||||
run: php ./vendor/phpunit/phpunit/phpunit
|
||||
|
6
.gitignore
vendored
6
.gitignore
vendored
@ -1,14 +1,8 @@
|
||||
|
||||
.idea/
|
||||
|
||||
# Smarty
|
||||
lexer/*.php
|
||||
lexer/*.php.bak
|
||||
lexer/*.out
|
||||
|
||||
/site
|
||||
|
||||
# Dev
|
||||
phpunit*
|
||||
.phpunit.result.cache
|
||||
vendor/*
|
||||
|
61
CHANGELOG.md
61
CHANGELOG.md
@ -6,6 +6,63 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Added support for PHP8.2
|
||||
- Added a new way to extend Smarty functionality using `Smarty::addExtension()` or `Smarty::setExtensions()`. Please see the docs for more information.
|
||||
- Custom tags can accept positional parameters, so you can write a block compiler that support this: `{trans "Jack" "dull boy"}All work and no play makes %s a %s.{/trans}` [#164](https://github.com/smarty-php/smarty/issues/164)
|
||||
- Full support for ternary operator: `{$test ? $a : $b}` and `{$var ?: $value_if_falsy}` [#881](https://github.com/smarty-php/smarty/issues/881)
|
||||
- Full support for null coalescing operator: `{$var ?? $value_if_null}` [#882](https://github.com/smarty-php/smarty/issues/882)
|
||||
|
||||
### 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 reliably generated from sources (.y and .plex) using the make file
|
||||
- Smarty now always runs in multibyte mode, using `symfony/polyfill-mbstring` if required. Please use the
|
||||
multibyte extension for optimal performance.
|
||||
- Smarty no longer calls `mb_internal_encoding()` and doesn't check for deprecated `mbstring.func_overload` ini directive [#480](https://github.com/smarty-php/smarty/issues/480)
|
||||
- Generated `<script>` tags lo longer have deprecated `type="text/javascript"` or `language="Javascript"` attributes [#815](https://github.com/smarty-php/smarty/issues/815)
|
||||
- Smarty will throw a compiler exception insteadd of silently ignoring a modifier on a function call, like this: `{include|dot:"x-template-id" file="included.dot.tpl"}` [#526](https://github.com/smarty-php/smarty/issues/526)
|
||||
- The documentation was largely rewritten
|
||||
|
||||
### 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`.
|
||||
- You can no longer use native PHP-functions or userland functions in your templates without registering them. If you need a function in your templates,
|
||||
register it first.
|
||||
- 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->_current_file`
|
||||
- Removed `$smarty->allow_ambiguous_resources` (ambiguous resources handlers should still work)
|
||||
|
||||
### Fixed
|
||||
- `|strip_tags` does not work if the input is 0 [#890](https://github.com/smarty-php/smarty/issues/890)
|
||||
|
||||
@ -1790,7 +1847,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_Internal_Data so $smarty->assign('a',1)->assign('b',2); is possible now
|
||||
- added chaining to \Smarty\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
|
||||
@ -2125,7 +2182,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_Internal_Data
|
||||
- changed $tpl_vars, $config_vars and $parent to belong to \Smarty\Data
|
||||
- added Smarty::registerCacheResource() for dynamic cache resource object registration
|
||||
|
||||
27/12/2010
|
||||
|
25
Makefile
Normal file
25
Makefile
Normal file
@ -0,0 +1,25 @@
|
||||
all: lexers parsers
|
||||
|
||||
lexers: src/Lexer/ConfigfileLexer.php src/Lexer/TemplateLexer.php
|
||||
parsers: src/Parser/ConfigfileParser.php src/Parser/TemplateParser.php
|
||||
|
||||
docs:
|
||||
mike deploy 5.0
|
||||
|
||||
test-docs:
|
||||
mkdocs serve
|
||||
|
||||
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
|
@ -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 can be run with PHP 7.1 to PHP 8.2.
|
||||
Smarty v5 can be run with PHP 7.2 to PHP 8.2.
|
||||
|
||||
## Installation
|
||||
Smarty versions 3.1.11 or later can be installed with [Composer](https://getcomposer.org/).
|
||||
|
33
TODO.txt
Normal file
33
TODO.txt
Normal file
@ -0,0 +1,33 @@
|
||||
# @TODO
|
||||
|
||||
## CI-building optimization
|
||||
- compiled & cached templates should not contain references to local filesystem paths. Add an optional rootpath param
|
||||
to `(add|set)TemplateDir` or as a separate method. Make it default to `getcwd()`. If a relative path is passed to
|
||||
`(add|set)TemplateDir`, prefix it with the rootpath at runtime, but do not store the path.
|
||||
|
||||
## Review direct variable property access
|
||||
- review ->value{$index} in ForTag
|
||||
|
||||
## include inline
|
||||
- Re-introduce merge_compiled_includes and the {include inline} attribute?
|
||||
|
||||
## Output buffering
|
||||
- Fix ob_ output buffering commands being scattered around the codebase
|
||||
|
||||
## Review public static vars
|
||||
- such as _CHARSET and _IS_WINDOWS
|
||||
|
||||
## 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
|
||||
|
||||
## Beatify output
|
||||
- compiled templates could be proper classes, possibly using [nette/php-generator](https://packagist.org/packages/nette/php-generator)
|
||||
|
||||
## 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?
|
@ -30,20 +30,24 @@
|
||||
"forum": "https://github.com/smarty-php/smarty/discussions"
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.1 || ^8.0"
|
||||
"php": "^7.2 || ^8.0",
|
||||
"symfony/polyfill-mbstring": "^1.27"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": [
|
||||
"libs/"
|
||||
"psr-4" : {
|
||||
"Smarty\\" : "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions.php"
|
||||
]
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "4.0.x-dev"
|
||||
"dev-master": "5.0.x-dev"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^8.5 || ^7.5",
|
||||
"smarty/smarty-lexer": "^3.1"
|
||||
"smarty/smarty-lexer": "^4.0.2"
|
||||
}
|
||||
}
|
||||
|
@ -2,11 +2,11 @@
|
||||
/**
|
||||
* Example Application
|
||||
*
|
||||
* @package Example-application
|
||||
|
||||
*/
|
||||
require '../libs/Smarty.class.php';
|
||||
$smarty = new Smarty;
|
||||
//$smarty->force_compile = true;
|
||||
|
||||
$smarty = new \Smarty\Smarty;
|
||||
|
||||
$smarty->debugging = true;
|
||||
$smarty->caching = true;
|
||||
$smarty->cache_lifetime = 120;
|
||||
|
@ -1,101 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
@ -11,8 +11,6 @@
|
||||
|
||||
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>
|
||||
|
@ -3,15 +3,10 @@ services:
|
||||
base:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./utilities/testrunners/php71/Dockerfile
|
||||
dockerfile: ./utilities/testrunners/php72/Dockerfile
|
||||
volumes:
|
||||
- .:/app
|
||||
working_dir: /app
|
||||
php71:
|
||||
extends:
|
||||
service: base
|
||||
build:
|
||||
dockerfile: ./utilities/testrunners/php71/Dockerfile
|
||||
php72:
|
||||
extends:
|
||||
service: base
|
||||
|
92
docs/api/basics.md
Normal file
92
docs/api/basics.md
Normal file
@ -0,0 +1,92 @@
|
||||
# Basics
|
||||
|
||||
## Installation
|
||||
For installation instructies, please see the [getting started section](../getting-started.md).
|
||||
|
||||
## Rendering a template
|
||||
Here's how you create an instance of Smarty in your PHP scripts:
|
||||
```php
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
```
|
||||
|
||||
You now have a Smarty object that you can use to render templates.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->display('string:The current smarty version is: {$smarty.version}.');
|
||||
// or
|
||||
echo $smarty->fetch('string:The current smarty version is: {$smarty.version}.');
|
||||
```
|
||||
|
||||
## Using file-based templates
|
||||
You probably want to manage your templates as files. Create a subdirectory called 'templates' and
|
||||
then configure Smarty to use that:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setTemplateDir(__DIR__ . '/templates');
|
||||
```
|
||||
|
||||
Say you have a template file called 'version.tpl', stored in the 'templates' directory like this:
|
||||
```smarty
|
||||
<h1>Hi</h1>
|
||||
The current smarty version is: {$smarty.version|escape}.
|
||||
```
|
||||
|
||||
You can now render this, using:
|
||||
```php
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setTemplateDir(__DIR__ . '/templates');
|
||||
$smarty->display('version.tpl');
|
||||
```
|
||||
|
||||
## Assigning variables
|
||||
|
||||
Templates start to become really useful once you add variables to the mix.
|
||||
|
||||
Create a template called 'footer.tpl' in the 'templates' directory like this:
|
||||
```smarty
|
||||
<small>Copyright {$companyName|escape}</small>
|
||||
```
|
||||
|
||||
Now assign a value to the 'companyName' variable and render your template like this:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setTemplateDir(__DIR__ . '/templates');
|
||||
$smarty->assign('companyName', 'AC & ME Corp.');
|
||||
$smarty->display('footer.tpl');
|
||||
```
|
||||
|
||||
Run this, and you will see:
|
||||
|
||||
```html
|
||||
<small>Copyright AC & ME Corp.</small>
|
||||
```
|
||||
|
||||
Note how the [escape modifier](../designers/language-modifiers/language-modifier-escape.md)
|
||||
translated the `&` character into the proper HTML syntax `&`.
|
184
docs/api/caching/basics.md
Normal file
184
docs/api/caching/basics.md
Normal file
@ -0,0 +1,184 @@
|
||||
# Caching
|
||||
|
||||
Caching is used to speed up the rendering of a template by saving and re-using the output.
|
||||
|
||||
If a cached version of the call is available, that is displayed instead of
|
||||
regenerating the output. Caching can speed things up tremendously,
|
||||
especially templates with longer computation times.
|
||||
|
||||
Since templates can include or extend other templates, one
|
||||
cache file could conceivably be made up of several template files,
|
||||
config files, etc.
|
||||
|
||||
> ** Note **
|
||||
>
|
||||
> Since templates are dynamic, it is important to be careful what you are
|
||||
> caching and for how long. For instance, if you are displaying the front
|
||||
> page of your website that does not change its content very often, it
|
||||
> might work well to cache this page for an hour or more. On the other
|
||||
> hand, if you are displaying a page with a timetable containing new
|
||||
> information by the minute, it would not make sense to cache this page.
|
||||
|
||||
## Setting Up Caching
|
||||
|
||||
The first thing to do is enable caching by calling `Smarty::setCaching()` with either
|
||||
`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or `\Smarty\Smarty::CACHING_LIFETIME_SAVED`.
|
||||
Or with `\Smarty\Smarty::CACHING_OFF` to disable caching again.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// enable caching, using the current lifetime (see below)
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
// enable caching, using the lifetime set when the cache was saved (see below)
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);
|
||||
|
||||
// disable caching
|
||||
$smarty->setCaching(Smarty::CACHING_OFF);
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
With caching enabled, the function call to `$smarty->display('index.tpl')` will
|
||||
render the template as usual, but also saves a copy of its output. On the
|
||||
next call to `$smarty->display('index.tpl')`, the cached copy will be used
|
||||
instead of rendering the template again.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> By default, Smarty saved its caches as files in a dir called `cache` relative to the current
|
||||
> directory. The default directory can be changed using `$smarty->setCacheDir('/some/cache/dir');`
|
||||
> The files are named similar
|
||||
> to the template name. Although they end in the `.php` extension, they
|
||||
> are not intended to be directly executable. Do not edit these files!
|
||||
|
||||
## Cache lifetime
|
||||
|
||||
Each cached page has a limited lifetime. The default value is 3600
|
||||
seconds, or one hour. After that time expires, the cache is regenerated.
|
||||
|
||||
You can change the lifetime as follows:
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
// or $smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);
|
||||
|
||||
// set the cache_lifetime to 5 minutes
|
||||
$smarty->setCacheLifetime(5 * 60);
|
||||
```
|
||||
|
||||
Setting caching to a value of `\Smarty\Smarty::CACHING_LIFETIME_CURRENT` tells Smarty to use
|
||||
the current lifetime to determine if the cache has expired.
|
||||
|
||||
A value of `\Smarty\Smarty::CACHING\_LIFETIME\_SAVED` tells Smarty to use the lifetime value at the time the
|
||||
cache was generated. This way you can set the just before rendering a template to have granular control over
|
||||
when that particular cache expires.
|
||||
|
||||
An example:
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// retain current cache lifetime for each specific display call
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);
|
||||
|
||||
// set the cache_lifetime for index.tpl to 5 minutes
|
||||
$smarty->setCacheLifetime(300);
|
||||
$smarty->display('index.tpl');
|
||||
|
||||
// set the cache_lifetime for home.tpl to 1 hour
|
||||
$smarty->setCacheLifetime(3600);
|
||||
$smarty->display('home.tpl');
|
||||
|
||||
// NOTE: the following $cache_lifetime setting will not work when $caching
|
||||
// is set to Smarty::CACHING_LIFETIME_SAVED.
|
||||
// The cache lifetime for home.tpl has already been set
|
||||
// to 1 hour, and will no longer respect the value of $cache_lifetime.
|
||||
// The home.tpl cache will still expire after 1 hour.
|
||||
$smarty->setCacheLifetime(30); // 30 seconds
|
||||
$smarty->display('home.tpl');
|
||||
```
|
||||
|
||||
## Compile check
|
||||
|
||||
By default, every template file and config file that is involved with the cache file
|
||||
is checked for modification. If any of the files have been modified
|
||||
since the cache was generated, the cache is immediately regenerated.
|
||||
|
||||
This is a computational overhead, so for optimum performance, disable this on a production environment:
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
$smarty->setCompileCheck(Smarty::COMPILECHECK_OFF);
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
## Checking if a template is cached
|
||||
|
||||
Smarty's `isCached() method can be used to test if a
|
||||
template has a valid cache or not. If you have a cached template that
|
||||
requires something like a database fetch, you can use this to skip that
|
||||
process.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
if (!$smarty->isCached('index.tpl')) {
|
||||
// No cache available, do variable assignments here.
|
||||
$smarty->assign('data', do_expensive_database_calls());
|
||||
}
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
## Nocache-blocks
|
||||
You can keep parts of a page dynamic (disable caching) with the
|
||||
[`{nocache}{/nocache}`](../../designers/language-builtin-functions/language-function-nocache.md) block function,
|
||||
or by using the `nocache` parameter for most template functions.
|
||||
|
||||
Let's say the whole page can be cached except for a banner that is
|
||||
displayed down the side of the page. By using a [`{nocache}{/nocache}`](../../designers/language-builtin-functions/language-function-nocache.md)
|
||||
block for the banner, you can
|
||||
keep this element dynamic within the cached content.
|
||||
|
||||
## Clearing the cache
|
||||
You can clear all the cache files with Smarty's `clearAllCache()` method, or individual cache
|
||||
files with the `clearCache()` method.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
// clear only cache for index.tpl
|
||||
$smarty->clearCache('index.tpl');
|
||||
|
||||
// clear out all cache files
|
||||
$smarty->clearAllCache();
|
||||
|
||||
// clear out all cache files older than one hour
|
||||
$smarty->clearAllCache(3600);
|
||||
|
||||
// or, clear all expired caches
|
||||
$smarty->clearAllCache(Smarty::CLEAR_EXPIRED);
|
||||
```
|
||||
|
||||
|
36
docs/api/caching/custom-storage-layers.md
Normal file
36
docs/api/caching/custom-storage-layers.md
Normal file
@ -0,0 +1,36 @@
|
||||
# Custom cache storage layers
|
||||
|
||||
As an alternative to using the default file-based caching mechanism, you
|
||||
can specify a custom cache implementation that will be used to read,
|
||||
write and clear cached files.
|
||||
|
||||
With a custom cache implementation you could replace the slow filesystem by a
|
||||
faster storage engine, centralize the cache to be accessible to multiple
|
||||
servers.
|
||||
|
||||
Smarty requires implementations to extend `\Smarty\Cacheresource\Base`, but encourages you to either extend
|
||||
`\Smarty\Cacheresource\Custom` or `\Smarty\Cacheresource\KeyValueStore`.
|
||||
|
||||
- `\Smarty\Cacheresource\Custom` is a simple API directing all read, write,
|
||||
clear calls to your implementation. This API allows you to store
|
||||
wherever and however you deem fit.
|
||||
- `\Smarty\Cacheresource\KeyValueStore` allows you to turn any
|
||||
KeyValue-Store (like APC or Memcache) into a full-featured
|
||||
CacheResource implementation. Everything around deep
|
||||
cache-groups like "a|b|c" is being handled for you in a way that
|
||||
guarantees clearing the cache-group "a" will clear all nested groups
|
||||
as well - even though KeyValue-Stores don't allow this kind of
|
||||
hierarchy by nature.
|
||||
|
||||
Custom CacheResources must be registered on
|
||||
runtime with `Smarty\Smarty::setCacheResource()`:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setCacheResource(new My_CacheResource_Mysql());
|
||||
```
|
||||
|
137
docs/api/caching/multiple-caches-per-template.md
Normal file
137
docs/api/caching/multiple-caches-per-template.md
Normal file
@ -0,0 +1,137 @@
|
||||
# Multiple caches per template
|
||||
|
||||
## Introduction
|
||||
|
||||
You can have multiple cache files for a single call to
|
||||
`display()` or `fetch()`.
|
||||
|
||||
Let's say that
|
||||
a call to `$smarty->display('index.tpl')` may have several different output
|
||||
contents depending on some condition, and you want separate caches for
|
||||
each one. You can do this by passing a `$cache_id` as the second
|
||||
parameter to the function call:
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
$my_cache_id = (int) $_GET['article_id'];
|
||||
|
||||
$smarty->display('index.tpl', $my_cache_id);
|
||||
```
|
||||
|
||||
|
||||
Above, we are passing the variable `$my_cache_id` to
|
||||
[`display()`](#api.display) as the `$cache_id`. For each unique value of
|
||||
`$my_cache_id`, a separate cache will be generated for `index.tpl`. In
|
||||
this example, `article_id` was passed in the URL and is used as the
|
||||
`$cache_id`.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Be very cautious when passing values from a client (web browser) into
|
||||
> Smarty or any PHP application. Although the above example of using the
|
||||
> article_id from the URL looks handy, it could have bad consequences.
|
||||
> The `$cache_id` is used to create a directory on the file system, so
|
||||
> if the user decided to write a script that sends random article_id's at a rapid pace,
|
||||
> this could possibly cause problems at the server level.
|
||||
> Be sure to sanitize any data passed in before using it. In this example, you might want to check if
|
||||
> the article_id is a valid ID in the database.
|
||||
|
||||
Be sure to pass the same `$cache_id` as the second parameter to
|
||||
`isCached()` and `clearCache()`.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
$my_cache_id = (int) $_GET['article_id'];
|
||||
|
||||
if (!$smarty->isCached('index.tpl', $my_cache_id)) {
|
||||
// ...
|
||||
}
|
||||
|
||||
$smarty->display('index.tpl', $my_cache_id);
|
||||
```
|
||||
|
||||
## Clearing specific caches
|
||||
|
||||
You can clear all caches for a particular `$cache_id` by passing NULL as
|
||||
the first parameter to `clearCache()`.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
// clear all caches with "sports" as the $cache_id
|
||||
$smarty->clearCache(null, 'sports');
|
||||
|
||||
$smarty->display('index.tpl', 'sports');
|
||||
```
|
||||
|
||||
In this manner, you can "group" your caches together by giving them the
|
||||
same `$cache_id`.
|
||||
|
||||
## Advanced cache grouping
|
||||
|
||||
You can do more elaborate grouping by setting up `$cache_id` groups.
|
||||
This is accomplished by separating each sub-group with a vertical bar
|
||||
`|` in the `$cache_id` value. You can have as many sub-groups as you
|
||||
like.
|
||||
|
||||
- You can think of cache groups like a directory hierarchy. For
|
||||
instance, a cache group of `'a|b|c'` could be thought of as the
|
||||
directory structure `'/a/b/c/'`.
|
||||
|
||||
- `clearCache(null, 'a|b|c')` would be like removing the files
|
||||
`'/a/b/c/*'`. `clearCache(null, 'a|b')` would be like removing the
|
||||
files `'/a/b/*'`.
|
||||
|
||||
- If you specify a template name such as
|
||||
`clearCache('foo.tpl', 'a|b|c')` then Smarty will attempt to remove
|
||||
`'/a/b/c/foo.tpl'`.
|
||||
|
||||
- You CANNOT remove a specified template name under multiple cache
|
||||
groups such as `'/a/b/*/foo.tpl'`, the cache grouping works
|
||||
left-to-right ONLY. You will need to group your templates under a
|
||||
single cache group hierarchy to be able to clear them as a group.
|
||||
|
||||
Cache grouping should not be confused with your template directory
|
||||
hierarchy, the cache grouping has no knowledge of how your templates are
|
||||
structured. So for example, if you have a template structure like
|
||||
`themes/blue/index.tpl` and you want to be able to clear all the cache
|
||||
files for the "blue" theme, you will need to create a cache group
|
||||
structure that mimics your template file structure, such as
|
||||
`display('themes/blue/index.tpl', 'themes|blue')`, then clear them with
|
||||
`clearCache(null, 'themes|blue')`.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
|
||||
|
||||
// clear all caches with 'sports|basketball' as the first two cache_id groups
|
||||
$smarty->clearCache(null, 'sports|basketball');
|
||||
|
||||
// clear all caches with "sports" as the first cache_id group. This would
|
||||
// include "sports|basketball", or "sports|(anything)|(anything)|(anything)|..."
|
||||
$smarty->clearCache(null, 'sports');
|
||||
|
||||
// clear the foo.tpl cache file with "sports|basketball" as the cache_id
|
||||
$smarty->clearCache('foo.tpl', 'sports|basketball');
|
||||
|
||||
$smarty->display('index.tpl', 'sports|basketball');
|
||||
```
|
||||
|
||||
|
175
docs/api/configuring.md
Normal file
175
docs/api/configuring.md
Normal file
@ -0,0 +1,175 @@
|
||||
# Configuring Smarty
|
||||
|
||||
## Setting the template path
|
||||
By default, Smarty looks for templates to render in `./templates`.
|
||||
|
||||
You can change this, or even use multiple paths to use when looking for templates.
|
||||
|
||||
If you need to change this, you can use `setTemplateDir()` or `addTemplateDir()`.
|
||||
Use `getTemplateDir()` to retrieve the configured paths.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// set a single directory where the config files are stored
|
||||
$smarty->setTemplateDir('./config');
|
||||
|
||||
// set multiple directories where config files are stored
|
||||
$smarty->setTemplateDir(['./config', './config_2', './config_3']);
|
||||
|
||||
// add directory where config files are stored to the current list of dirs
|
||||
$smarty->addTemplateDir('./config_1');
|
||||
|
||||
// add multiple directories to the current list of dirs
|
||||
$smarty->addTemplateDir([
|
||||
'./config_2',
|
||||
'./config_3',
|
||||
]);
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./config')
|
||||
->addTemplateDir('./config_1')
|
||||
->addTemplateDir('./config_2');
|
||||
|
||||
// get all directories where config files are stored
|
||||
$template_dirs = $smarty->getTemplateDir();
|
||||
var_dump($template_dirs); // array
|
||||
|
||||
// get directory identified by key
|
||||
$template_dir = $smarty->getTemplateDir(0);
|
||||
var_dump($template_dir); // string
|
||||
```
|
||||
|
||||
## Setting the path for compiled templates
|
||||
Smarty compiles templates to native PHP to be as fast as possible.
|
||||
The default path where these PHP-files are stored is `./templates_c`.
|
||||
|
||||
If you need to change this, you can use `setCompileDir()`.
|
||||
Use `getCompileDir()` to retrieve the configured path.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// set another path to store compiled templates
|
||||
$smarty->setCompileDir('/data/compiled_templates');
|
||||
|
||||
// get directory where compiled templates are stored
|
||||
$compileDir = $smarty->getCompileDir();
|
||||
```
|
||||
|
||||
|
||||
## Setting the config path
|
||||
Smarty can [load data from config files](./variables/config-files.md).
|
||||
By default, Smarty loads the config files from `./configs`.
|
||||
|
||||
You can change this, or even use multiple paths to use when looking for config files.
|
||||
|
||||
If you need to change this, you can use `setConfigDir()` or `addConfigDir()`.
|
||||
Use `getConfigDir()` to retrieve the configured paths.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// set a single directory where the config files are stored
|
||||
$smarty->setConfigDir('./config');
|
||||
|
||||
// set multiple directories where config files are stored
|
||||
$smarty->setConfigDir(['./config', './config_2', './config_3']);
|
||||
|
||||
// add directory where config files are stored to the current list of dirs
|
||||
$smarty->addConfigDir('./config_1');
|
||||
|
||||
// add multiple directories to the current list of dirs
|
||||
$smarty->addConfigDir([
|
||||
'./config_2',
|
||||
'./config_3',
|
||||
]);
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setConfigDir('./config')
|
||||
->addConfigDir('./config_1', 'one')
|
||||
->addConfigDir('./config_2', 'two');
|
||||
|
||||
// get all directories where config files are stored
|
||||
$config_dirs = $smarty->getConfigDir();
|
||||
var_dump($config_dirs); // array
|
||||
|
||||
// get directory identified by key
|
||||
$config_dir = $smarty->getConfigDir(0);
|
||||
var_dump($config_dir); // string
|
||||
```
|
||||
|
||||
## Setting the path for caches
|
||||
Even though Smarty runs templates as native PHP for maximum speed, it still needs to
|
||||
execute the PHP code on each call. If your data doesn't change all that often, you
|
||||
may be able to speed up your application even more by using output caching.
|
||||
|
||||
Output caching can be a tricky subject, so we devoted an entire [section to caching](./caching/basics.md).
|
||||
Be sure to read that if you want to use caching.
|
||||
|
||||
By default, Smarty stores caches to PHP-files in a subdirectory named `./cache`.
|
||||
|
||||
If you need to change this, you can use `setCacheDir()`.
|
||||
Use `getCacheDir()` to retrieve the configured path.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// set another path to store caches
|
||||
$smarty->setCacheDir('/data/caches');
|
||||
|
||||
// get directory where cached templates are stored
|
||||
$cacheDir = $smarty->getCacheDir();
|
||||
```
|
||||
|
||||
## Disabling compile check
|
||||
By default, Smarty tests to see if the
|
||||
current template has changed since the last time
|
||||
it was compiled. If it has changed, it recompiles that template.
|
||||
|
||||
Once an application is put into production, this compile-check step
|
||||
is usually no longer needed and the extra checks can significantly hurt performance.
|
||||
Be sure to disable compile checking on production for maximum performance.
|
||||
```php
|
||||
<?php
|
||||
$smarty->setCompileCheck(\Smarty\Smarty::COMPILECHECK_OFF);
|
||||
```
|
||||
|
||||
If [`caching`](./caching/basics.md) is enabled and compile-check is
|
||||
enabled, then the cache files will get regenerated if an involved
|
||||
template file or config file was updated.
|
||||
|
||||
## Charset encoding
|
||||
|
||||
There are a variety of encodings for textual data, ISO-8859-1 (Latin1)
|
||||
and UTF-8 being the most popular. Unless you change `\Smarty\Smarty::$_CHARSET`,
|
||||
Smarty recognizes `UTF-8` as the internal charset.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> `ISO-8859-1` has been PHP\'s default internal charset since the
|
||||
> beginning. Unicode has been evolving since 1991. Since then, it has
|
||||
> become the one charset to conquer them all, as it is capable of
|
||||
> encoding most of the known characters even across different character
|
||||
> systems (latin, cyrillic, japanese, ...). `UTF-8` is unicode\'s most
|
||||
> used encoding, as it allows referencing the thousands of character
|
||||
> with the smallest size overhead possible.
|
||||
>
|
||||
> Since unicode and UTF-8 are very widespread nowadays, their use is
|
||||
> strongly encouraged.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Smarty\'s internals and core plugins are truly UTF-8 compatible since
|
||||
> Smarty 3.1.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// use japanese character encoding
|
||||
mb_internal_charset('EUC-JP');
|
||||
|
||||
\Smarty\Smarty::$_CHARSET = 'EUC-JP';
|
||||
$smarty = new \Smarty\Smarty();
|
||||
```
|
||||
|
59
docs/api/extending/block-tags.md
Normal file
59
docs/api/extending/block-tags.md
Normal file
@ -0,0 +1,59 @@
|
||||
# Custom block tags
|
||||
|
||||
Block tags are tags of the form: `{func} .. {/func}`. In other
|
||||
words, they enclose a template block and operate on the contents of this
|
||||
block.
|
||||
|
||||
Block functions take precedence over normal tags of the same name, that is, you
|
||||
cannot have both custom tag `{func}` and block tag `{func}..{/func}`.
|
||||
|
||||
- By default, your function implementation is called twice by Smarty:
|
||||
once for the opening tag, and once for the closing tag. (See
|
||||
`$repeat` below on how to change this.)
|
||||
|
||||
- Only the opening tag of the block has attributes. All attributes are contained in the `$params`
|
||||
variable as an associative array. The opening tag attributes are
|
||||
also accessible to your function when processing the closing tag.
|
||||
|
||||
- The value of the `$content` variable depends on whether your
|
||||
function is called for the opening or closing tag. In case of the
|
||||
opening tag, it will be NULL, and in case of the closing tag it will
|
||||
be the contents of the template block. Note that the template block
|
||||
will have already been processed by Smarty, so all you will receive
|
||||
is the template output, not the template source.
|
||||
|
||||
- The parameter `$repeat` is passed by reference to the function
|
||||
implementation and provides a possibility for it to control how many
|
||||
times the block is displayed. By default `$repeat` is TRUE at the
|
||||
first call of the block function (the opening tag) and FALSE on all
|
||||
subsequent calls to the block function (the block's closing tag).
|
||||
Each time the function implementation returns with `$repeat` being
|
||||
TRUE, the contents between `{func}...{/func}` are evaluated and the
|
||||
function implementation is called again with the new block contents
|
||||
in the parameter `$content`.
|
||||
|
||||
Example:
|
||||
```php
|
||||
<?php
|
||||
|
||||
function smarty_block_translate($params, $content, \Smarty\Template $template, &$repeat) {
|
||||
// only output on the closing tag
|
||||
if (!$repeat){
|
||||
if (isset($content)) {
|
||||
$lang = $params['lang'];
|
||||
// do some intelligent translation thing here with $content
|
||||
return $translation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$smarty->registerPlugin(Smarty\Smarty::PLUGIN_BLOCK, 'translate', 'smarty_block_translate');
|
||||
```
|
||||
|
||||
This can now be used in your templates as follows:
|
||||
|
||||
```smarty
|
||||
{translate lang='nl'}
|
||||
Quia omnis nulla omnis iusto est id et.
|
||||
{/translate}
|
||||
```
|
101
docs/api/extending/extensions.md
Normal file
101
docs/api/extending/extensions.md
Normal file
@ -0,0 +1,101 @@
|
||||
# Creating an extension
|
||||
|
||||
## Default extensions
|
||||
|
||||
In order to organize your custom tags and modifiers, you can create an Extension.
|
||||
In fact, most of Smarty itself is organized into two extensions:
|
||||
|
||||
- the core extension, which provides the basic language tags such as `{if}`, `{for}` and `{assign}`.
|
||||
- the default extension, which provides all default modifiers such as `|escape`, `|nl2br` and `|number_format`
|
||||
and tags such as `{html_image}`, `{mailto}` and `{textformat}` that are enabled by default, but not necessarily universal.
|
||||
|
||||
> ** Note **
|
||||
>
|
||||
> There is also the 'BCPluginsAdapter' extension, which does not add any new functionality, but
|
||||
> wraps calls to deprecated methods such as `Smarty\Smarty::addPluginsDir()` and `Smarty\Smarty::loadFilter()`.
|
||||
|
||||
## Writing your own extension
|
||||
|
||||
In order to write your own custom extension, you must write a class that implements `Smarty\Extension\ExtensionInterface`.
|
||||
However, it is usually easier to extend `Smarty\Extension\Base` which provides empty implementation for each of the methods
|
||||
required by `Smarty\Extension\ExtensionInterface`. This allows you to only override the method(s) you need.
|
||||
|
||||
Example:
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Extension\Base;
|
||||
|
||||
class MyExtension extends Base {
|
||||
|
||||
public function getModifierCompiler(string $modifier): ?\Smarty\Compile\Modifier\ModifierCompilerInterface {
|
||||
|
||||
switch ($modifier) {
|
||||
case 'array_escape': return new MyArrayEscapeModifierCompiler();
|
||||
case 'array_unescape': return new MyArrayUnescapeModifierCompiler();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
Another example, that would allow you to use any valid PHP callable as a modifier in your templates:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Extension\Base;
|
||||
|
||||
class MyCallablePassThroughExtension extends Base {
|
||||
|
||||
public function getModifierCallback(string $modifierName) {
|
||||
|
||||
if (is_callable($modifierName)) {
|
||||
return $modifierName;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Writing an extension allows you to add a group of tags, block tags and modifiers to the Smarty language.
|
||||
It also allows you to register pre-, post- and output-filters in a structured way.
|
||||
The files in `src/Extension/` in the `smarty/smarty` dir should give you all the information you need to start
|
||||
writing your own extension.
|
||||
|
||||
## Registering an extension
|
||||
|
||||
When you have written your extension, add it to a Smarty instance as follows:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->addExtension(new MyCustomExtension());
|
||||
```
|
||||
|
||||
This will add `MyCustomExtension` to the end of the extension list, meaning that you cannot override tags or modifiers
|
||||
from one of Smarty's default extensions.
|
||||
|
||||
Should you wish to insert your extension at the top of the extension list, or create a very limited Smarty version that
|
||||
only contains the core extension, you can use `Smarty\Smarty::setExtensions()` to override the list of extensions.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setExtensions([
|
||||
new Smarty\Extension\CoreExtension(),
|
||||
new MyCustomExtension(),
|
||||
new Smarty\Extension\DefaultExtension(),
|
||||
]);
|
||||
```
|
10
docs/api/extending/introduction.md
Normal file
10
docs/api/extending/introduction.md
Normal file
@ -0,0 +1,10 @@
|
||||
# Extending Smarty
|
||||
|
||||
By default, Smarty is already very complete and powerful. However, you can unlock its real potential by
|
||||
extending Smarty.
|
||||
|
||||
There are various ways to extend Smarty for it to suit your needs. You can create custom
|
||||
[tags](tags.md), [block tags](block-tags.md) and [modifiers](modifiers.md) by registering a method as a plugin.
|
||||
|
||||
If this becomes too messy, you can group your custom tags, modifiers, and more into an [Extension](extensions.md).
|
||||
|
27
docs/api/extending/modifiers.md
Normal file
27
docs/api/extending/modifiers.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Custom modifiers
|
||||
|
||||
Modifiers are little functions that are applied
|
||||
to a variable in the template before it is displayed or used in some
|
||||
other context. Smarty comes with a bunch of [modifiers](../../designers/language-modifiers/index.md), but you can
|
||||
easily add your own.
|
||||
|
||||
In order to do so, you must write a function that accepts as its first parameter the value on which the
|
||||
modifier is to operate. The rest of the parameters are optional, depending on what kind of operation is to be performed.
|
||||
|
||||
The modifier has to return the result of its processing.
|
||||
|
||||
For example:
|
||||
```php
|
||||
<?php
|
||||
|
||||
function smarty_modifier_substr($string, $offset, $length) {
|
||||
return substr($string, $offset, $length);
|
||||
}
|
||||
|
||||
$smarty->registerPlugin(Smarty\Smarty::PLUGIN_MODIFIER, 'substr', 'smarty_modifier_substr');
|
||||
```
|
||||
|
||||
You can now use this in your templates as follows:
|
||||
```smarty
|
||||
{$applicationName|substr:0:20}
|
||||
```
|
84
docs/api/extending/tags.md
Normal file
84
docs/api/extending/tags.md
Normal file
@ -0,0 +1,84 @@
|
||||
# Custom tags
|
||||
|
||||
You can add your own tags to the Smarty language.
|
||||
|
||||
## Runtime tags
|
||||
|
||||
Usually, you'll add a runtime tag. Adding a runtime tag requires you to provide a callback function that accepts
|
||||
two parameters:
|
||||
|
||||
- `$params`: all attributes from the template as an associative array.
|
||||
- `$template`: a `Smarty\Template` object representing the template where tag was used.
|
||||
|
||||
The output (return value) of the function will be substituted in place
|
||||
of the tag in the template.
|
||||
|
||||
If the function needs to assign some variables to the template or use
|
||||
some other Smarty-provided functionality, it can use the supplied
|
||||
`$template` object to do so.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
function smarty_tag_eightball($params, \Smarty\Template $template): string {
|
||||
$answers = [
|
||||
'Yes',
|
||||
'No',
|
||||
'No way',
|
||||
'Outlook not so good',
|
||||
'Ask again soon',
|
||||
'Maybe in your reality'
|
||||
];
|
||||
|
||||
$result = array_rand($answers);
|
||||
return $answers[$result];
|
||||
}
|
||||
|
||||
$smarty->registerPlugin(Smarty\Smarty::PLUGIN_FUNCTION, 'eightball', 'smarty_tag_eightball');
|
||||
```
|
||||
|
||||
Which can now be used in the template as:
|
||||
|
||||
```smarty
|
||||
Question: Will we ever have time travel?
|
||||
Answer: {eightball}.
|
||||
```
|
||||
|
||||
## Compiler tags
|
||||
|
||||
Compiler tags are called only during compilation of the template.
|
||||
|
||||
They are useful for injecting PHP code or time-sensitive static content
|
||||
into the template. If there is both a compiler function and a runtime tag registered under the same name,
|
||||
the compiler function has precedence.
|
||||
|
||||
The compiler function is passed two parameters: the params array which
|
||||
contains precompiled strings for the attribute values and the Smarty
|
||||
object. It's supposed to return the code to be injected into the
|
||||
compiled template including the surrounding PHP tags.
|
||||
|
||||
Example:
|
||||
```php
|
||||
<?php
|
||||
|
||||
function smarty_compiler_tplheader($params, Smarty $smarty) {
|
||||
return "<?php\necho '" . $smarty->_current_file . " compiled at " . date('Y-m-d H:M'). "';\n?>";
|
||||
}
|
||||
|
||||
$smarty->registerPlugin(Smarty\Smarty::PLUGIN_COMPILER, 'tplheader', 'smarty_compiler_tplheader');
|
||||
```
|
||||
|
||||
This function can be called from the template as:
|
||||
|
||||
```smarty
|
||||
{* this function gets executed at compile time only *}
|
||||
{tplheader}
|
||||
```
|
||||
|
||||
The resulting PHP code in the compiled template would be something like
|
||||
this:
|
||||
|
||||
```php
|
||||
<?php
|
||||
echo 'index.tpl compiled at 2023-02-20 20:02';
|
||||
```
|
35
docs/api/filters/output-filters.md
Normal file
35
docs/api/filters/output-filters.md
Normal file
@ -0,0 +1,35 @@
|
||||
# Output filters
|
||||
|
||||
When a template is rendered, its output can be sent through one or more
|
||||
output filters.
|
||||
|
||||
> **Note**
|
||||
> This differs from [`prefilters`](prefilters.md) and
|
||||
> [`postfilters`](postfilters.md) because, pre- and postfilters
|
||||
> operate on compiled templates before they are saved to the disk, whereas
|
||||
> output filters operate on the template output when it is executed.
|
||||
|
||||
Smarty will pass the template output as the first argument, and expect the function
|
||||
to return the result of the processing.
|
||||
|
||||
Output filters can be either added as part of an [Extension](../extending/extensions.md) or
|
||||
registered as shown below.
|
||||
|
||||
This will provide a rudimentary protection against spambots:
|
||||
```php
|
||||
<?php
|
||||
|
||||
function protect_email($tpl_output, \Smarty\Template\ $template)
|
||||
{
|
||||
return preg_replace(
|
||||
'!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
|
||||
'$1%40$2',
|
||||
$tpl_output
|
||||
);
|
||||
}
|
||||
|
||||
// register the outputfilter
|
||||
$smarty->registerFilter("output", "protect_email");
|
||||
$smarty->display("index.tpl');
|
||||
|
||||
```
|
33
docs/api/filters/postfilters.md
Normal file
33
docs/api/filters/postfilters.md
Normal file
@ -0,0 +1,33 @@
|
||||
# Postfilters
|
||||
|
||||
Template postfilters are PHP functions that your templates are ran
|
||||
through *after they are compiled*.
|
||||
|
||||
Smarty will
|
||||
pass the compiled template code as the first argument, and expect the
|
||||
function to return the result of the processing, which must also be valid PHP code.
|
||||
|
||||
Prefilters can be either added as part of an [Extension](../extending/extensions.md) or
|
||||
registered as shown below.
|
||||
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
function add_header_comment($tpl_source, \Smarty\Template\ $template)
|
||||
{
|
||||
return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source;
|
||||
}
|
||||
|
||||
// register the postfilter
|
||||
$smarty->registerFilter('post', 'add_header_comment');
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
The postfilter above will make the compiled Smarty template `index.tpl`
|
||||
look like:
|
||||
|
||||
```smarty
|
||||
<!-- Created by Smarty! -->
|
||||
{* rest of template content... *}
|
||||
```
|
26
docs/api/filters/prefilters.md
Normal file
26
docs/api/filters/prefilters.md
Normal file
@ -0,0 +1,26 @@
|
||||
# Prefilters
|
||||
|
||||
Template prefilters are PHP functions that your templates are ran
|
||||
through *before they are compiled*. This is good for preprocessing your
|
||||
templates to remove unwanted comments, keeping an eye on what people are
|
||||
putting in their templates, etc.
|
||||
|
||||
Smarty will pass the template source code as the first argument, and
|
||||
expect the function to return the resulting template source code.
|
||||
|
||||
Prefilters can be either added as part of an [Extension](../extending/extensions.md) or
|
||||
registered as shown below.
|
||||
|
||||
This will remove all the html comments in the template source:
|
||||
```php
|
||||
<?php
|
||||
|
||||
function remove_dw_comments($tpl_source, \Smarty\Template\ $template)
|
||||
{
|
||||
return preg_replace("/<!--#.*-->/U",'',$tpl_source);
|
||||
}
|
||||
|
||||
// register the prefilter
|
||||
$smarty->registerFilter('pre', 'remove_dw_comments');
|
||||
$smarty->display('index.tpl');
|
||||
```
|
130
docs/api/inheritance.md
Normal file
130
docs/api/inheritance.md
Normal file
@ -0,0 +1,130 @@
|
||||
# Template Inheritance
|
||||
|
||||
Inheritance allows you to define base templates that can
|
||||
be extended by child templates. Extending means that the child template
|
||||
can override all or some of the named block areas in the base template.
|
||||
|
||||
When you render the child template, the result will as if you rendered
|
||||
the base template, with only the block(s) that you have overridden in the
|
||||
child templates differing.
|
||||
|
||||
- The inheritance tree can be as deep as you want, meaning you can
|
||||
extend a file that extends another one that extends another one and
|
||||
so on.
|
||||
|
||||
- The child templates can not define any content besides what's
|
||||
inside [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags they override.
|
||||
Anything outside of [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags will
|
||||
be removed.
|
||||
|
||||
- Template inheritance is a compile time process which creates a
|
||||
single compiled template file. Compared to corresponding solutions
|
||||
based on subtemplates included with the
|
||||
[`{include}`](../designers/language-builtin-functions/language-function-include.md) tag it does have much
|
||||
better performance when rendering.
|
||||
|
||||
## Basic inheritance
|
||||
|
||||
First, create a base template with one or more [blocks](../designers/language-builtin-functions/language-function-block.md).
|
||||
Then, create a child template. The child template
|
||||
must have an [{extends} tag](../designers/language-builtin-functions/language-function-extends.md) on its first line.
|
||||
|
||||
The child template can redefine one or more blocks defined in the base template.
|
||||
|
||||
See below for a simple example.
|
||||
|
||||
layout.tpl (base)
|
||||
|
||||
```smarty
|
||||
<html>
|
||||
<head>
|
||||
<title>{block name=title}Default Page Title{/block}</title>
|
||||
{block name=head}{/block}
|
||||
</head>
|
||||
<body>
|
||||
{block name=body}{/block}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
|
||||
myproject.tpl (child)
|
||||
|
||||
```smarty
|
||||
{extends file='layout.tpl'}
|
||||
{block name=head}
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
{/block}
|
||||
```
|
||||
|
||||
mypage.tpl (grandchild)
|
||||
|
||||
```smarty
|
||||
{extends file='myproject.tpl'}
|
||||
{block name=title}My Page Title{/block}
|
||||
{block name=head}
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
{/block}
|
||||
{block name=body}My HTML Page Body goes here{/block}
|
||||
```
|
||||
|
||||
|
||||
To render the above, you would use:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->display('mypage.tpl');
|
||||
```
|
||||
|
||||
The resulting output is:
|
||||
|
||||
```html
|
||||
<html>
|
||||
<head>
|
||||
<title>My Page Title</title>
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
My HTML Page Body goes here
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> When [compile-check](./configuring.md#disabling-compile-check) is enabled, all files
|
||||
> in the inheritance tree
|
||||
> are checked for modifications upon each invocation. You may want to
|
||||
> disable compile-check on production servers for this reason.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> If you have a subtemplate which is included with
|
||||
> [`{include}`](../designers/language-builtin-functions/language-function-include.md) and it contains
|
||||
> [`{block}`](../designers/language-builtin-functions/language-function-block.md) areas it works only if the
|
||||
> [`{include}`](../designers/language-builtin-functions/language-function-include.md) itself is called from within
|
||||
> a surrounding [`{block}`](../designers/language-builtin-functions/language-function-block.md). In the final
|
||||
> parent template you may need a dummy
|
||||
> [`{block}`](../designers/language-builtin-functions/language-function-block.md) for it.
|
||||
|
||||
|
||||
## Using append and prepend
|
||||
The content of [`{block}`](../designers/language-builtin-functions/language-function-block.md) tags from child
|
||||
and parent templates can be merged by the `append` or `prepend`
|
||||
[`{block}`](../designers/language-builtin-functions/language-function-block.md) tag option flags and
|
||||
`{$smarty.block.parent}` or `{$smarty.block.child}` placeholders.
|
||||
|
||||
## Extends resource type
|
||||
Instead of using [`{extends}`](../designers/language-builtin-functions/language-function-extends.md) tags in the
|
||||
template files you can define the inheritance tree in your PHP script by
|
||||
using the [`extends:` resource](resources.md#the-extends-resource) type.
|
||||
|
||||
The code below will return same result as the example above.
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->display('extends:layout.tpl|myproject.tpl|mypage.tpl');
|
||||
```
|
86
docs/api/rendering.md
Normal file
86
docs/api/rendering.md
Normal file
@ -0,0 +1,86 @@
|
||||
# Rendering templates
|
||||
|
||||
## Fetching or rendering templates directly
|
||||
As explained in [basics](basics.md), you can use `$smarty->fetch()` or `$smarty->display()`
|
||||
to render a template directly.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->display('homepage.tpl');
|
||||
|
||||
// or
|
||||
|
||||
$output = $smarty->fetch('homepage.tpl');
|
||||
```
|
||||
|
||||
When you use `display()`, Smarty renders the template to the standard output stream.
|
||||
`fetch()` returns the output instead of echoing it.
|
||||
|
||||
The example above uses simple filenames to load the template. Smarty also supports
|
||||
[loading templates from resources](resources.md).
|
||||
|
||||
## Creating a template object
|
||||
You can also create a template object which later can be prepared first,
|
||||
and rendered later. This can be useful, for example if you plan to re-use several
|
||||
templates.
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// create template object with its private variable scope
|
||||
$tpl = $smarty->createTemplate('index.tpl');
|
||||
|
||||
// assign a variable (available only to this template)
|
||||
$tpl->assign('title', 'My Homepage!');
|
||||
|
||||
// display the template
|
||||
$tpl->display();
|
||||
```
|
||||
|
||||
More on assigning variables in [using data in templates](variables/assigning.md).
|
||||
|
||||
|
||||
## Testing if a template exists
|
||||
You can use `templateExists()` to check whether a template exists before you attempt to use it.
|
||||
|
||||
It accepts either a path to the template on the filesystem or a
|
||||
resource string specifying the template.
|
||||
|
||||
This example uses `$_GET['page']` to
|
||||
[`{include}`](../designers/language-builtin-functions/language-function-include.md) a content template. If the
|
||||
template does not exist then an error page is displayed instead. First,
|
||||
the `page_container.tpl`
|
||||
|
||||
```smarty
|
||||
<html>
|
||||
<head>
|
||||
<title>{$title|escape}</title>
|
||||
</head>
|
||||
<body>
|
||||
{* include middle content page *}
|
||||
{include file=$content_template}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
And the php script:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
// set the filename eg index.inc.tpl
|
||||
$mid_template = $_GET['page'].'.inc.tpl';
|
||||
|
||||
if (!$smarty->templateExists($mid_template)){
|
||||
$mid_template = 'page_not_found.tpl';
|
||||
}
|
||||
$smarty->assign('content_template', $mid_template);
|
||||
|
||||
$smarty->display('page_container.tpl');
|
||||
```
|
322
docs/api/resources.md
Normal file
322
docs/api/resources.md
Normal file
@ -0,0 +1,322 @@
|
||||
# Template resources
|
||||
|
||||
## The filesystem resource
|
||||
|
||||
So far in our examples, we have used simple filenames or paths when loading a template.
|
||||
|
||||
For example, to load a template file called `homepage.tpl`, from the filesystem, you could write:
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->display('homepage.tpl');
|
||||
```
|
||||
|
||||
The filesystem is the default resource. Templates, however, may come
|
||||
from a variety of sources. When you render a template, or
|
||||
when you include a template from within another template, you supply a
|
||||
resource type, followed by `:` and the appropriate path and template name.
|
||||
|
||||
If a resource is not explicitly given, the default resource type is assumed.
|
||||
The resource type for the filesystem is `file`, which means that the previous example
|
||||
can be rewritten as follows:
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->display('file:homepage.tpl');
|
||||
```
|
||||
|
||||
The file resource pulls templates source files from the directories
|
||||
specified using `Smarty::setTemplateDir()` (see [Configuring Smarty](configuring.md)).
|
||||
|
||||
`setTemplateDir` accepts a single path, but can also ben called with an array of paths.
|
||||
In that case, the list of directories is traversed in the order they appear in the array. The
|
||||
first template found is the one to process.
|
||||
|
||||
### Templates from a specific directory
|
||||
|
||||
Smarty 3.1 introduced the bracket-syntax for specifying an element from
|
||||
`Smarty::setTemplateDir()`. This allows websites
|
||||
employing multiple sets of templates better control over which template
|
||||
to access.
|
||||
|
||||
The bracket-syntax can be used as follows:
|
||||
```php
|
||||
<?php
|
||||
|
||||
// setup template directories
|
||||
$smarty->setTemplateDir([
|
||||
'./templates', // element: 0, index: 0
|
||||
'./templates_2', // element: 1, index: 1
|
||||
'10' => 'templates_10', // element: 2, index: '10'
|
||||
'foo' => 'templates_foo', // element: 3, index: 'foo'
|
||||
]);
|
||||
|
||||
/*
|
||||
assume the template structure
|
||||
./templates/foo.tpl
|
||||
./templates_2/foo.tpl
|
||||
./templates_2/bar.tpl
|
||||
./templates_10/foo.tpl
|
||||
./templates_10/bar.tpl
|
||||
./templates_foo/foo.tpl
|
||||
*/
|
||||
|
||||
// regular access
|
||||
$smarty->display('file:foo.tpl');
|
||||
// will load ./templates/foo.tpl
|
||||
|
||||
// using numeric index
|
||||
$smarty->display('file:[1]foo.tpl');
|
||||
// will load ./templates_2/foo.tpl
|
||||
|
||||
// using numeric string index
|
||||
$smarty->display('file:[10]foo.tpl');
|
||||
// will load ./templates_10/foo.tpl
|
||||
|
||||
// using string index
|
||||
$smarty->display('file:[foo]foo.tpl');
|
||||
// will load ./templates_foo/foo.tpl
|
||||
|
||||
// using "unknown" numeric index (using element number)
|
||||
$smarty->display('file:[2]foo.tpl');
|
||||
// will load ./templates_10/foo.tpl
|
||||
```
|
||||
|
||||
And, from within a Smarty template:
|
||||
|
||||
```smarty
|
||||
{include file="file:foo.tpl"}
|
||||
{* will load ./templates/foo.tpl *}
|
||||
|
||||
{include file="file:[1]foo.tpl"}
|
||||
{* will load ./templates_2/foo.tpl *}
|
||||
|
||||
{include file="file:[foo]foo.tpl"}
|
||||
{* will load ./templates_foo/foo.tpl *}
|
||||
```
|
||||
|
||||
### Using absolute paths
|
||||
|
||||
Templates outside the specified template directories
|
||||
require the `file:` template resource type, followed by the absolute
|
||||
path to the template (with leading slash).
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->display('file:/export/templates/index.tpl');
|
||||
$smarty->display('file:/path/to/my/templates/menu.tpl');
|
||||
````
|
||||
|
||||
And from within a Smarty template:
|
||||
```smarty
|
||||
{include file='file:/usr/local/share/templates/navigation.tpl'}
|
||||
```
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> With [`Security`](security.md) enabled, access to
|
||||
> templates outside of the specified templates directories is
|
||||
> not allowed unless you whitelist those directories.
|
||||
|
||||
### Windows file paths
|
||||
If you are running on Windows, file paths usually include a drive
|
||||
letter (such as `C:`) at the beginning of the pathname. Be sure to use `file:` in
|
||||
the path to avoid namespace conflicts and get the desired results.
|
||||
```php
|
||||
<?php
|
||||
$smarty->display('file:C:/export/templates/index.tpl');
|
||||
$smarty->display('file:F:/path/to/my/templates/menu.tpl');
|
||||
```
|
||||
|
||||
And from within Smarty template:
|
||||
```smarty
|
||||
{include file='file:D:/usr/local/share/templates/navigation.tpl'}
|
||||
```
|
||||
|
||||
### Handling missing templates
|
||||
If the file resource cannot find the requested template, it will check if there is
|
||||
a default template handler to call. By default, there is none, and Smarty will return an error,
|
||||
but you can register a default template handler calling `Smarty::registerDefaultTemplateHandler`
|
||||
with any [callable](https://www.php.net/manual/en/language.types.callable.php).
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
$smarty->registerDefaultTemplateHandler([$this, 'handleMissingTemplate']);
|
||||
|
||||
// ...
|
||||
|
||||
public function handleMissingTemplate($type, $name, &$content, &$modified, Smarty $smarty) {
|
||||
if (/* ... */) {
|
||||
// return corrected filepath
|
||||
return "/tmp/some/foobar.tpl";
|
||||
} elseif (/* ... */) {
|
||||
// return a template directly
|
||||
$content = "the template source";
|
||||
$modified = time();
|
||||
return true;
|
||||
} else {
|
||||
// tell smarty that we failed
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## The string and eval resources
|
||||
|
||||
Smarty can render templates from a string by using the `string:` or
|
||||
`eval:` resource.
|
||||
|
||||
- The `string:` resource behaves much the same as a template file. The
|
||||
template source is compiled from a string and stores the compiled
|
||||
template code for later reuse. Each unique template string will
|
||||
create a new compiled template file. If your template strings are
|
||||
accessed frequently, this is a good choice. If you have frequently
|
||||
changing template strings (or strings with low reuse value), the
|
||||
`eval:` resource may be a better choice, as it doesn\'t save
|
||||
compiled templates to disk.
|
||||
|
||||
- The `eval:` resource evaluates the template source every time a page
|
||||
is rendered. This is a good choice for strings with low reuse value.
|
||||
If the same string is accessed frequently, the `string:` resource
|
||||
may be a better choice.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> With a `string:` resource type, each unique string generates a
|
||||
> compiled file. Smarty cannot detect a string that has changed, and
|
||||
> therefore will generate a new compiled file for each unique string. It
|
||||
> is important to choose the correct resource so that you do not fill
|
||||
> your disk space with wasted compiled strings.
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->assign('foo', 'value');
|
||||
$template_string = 'display {$foo} here';
|
||||
$smarty->display('string:' . $template_string); // compiles for later reuse
|
||||
$smarty->display('eval:' . $template_string); // compiles every time
|
||||
```
|
||||
From within a Smarty template:
|
||||
```smarty
|
||||
{include file="string:$template_string"} {* compiles for later reuse *}
|
||||
{include file="eval:$template_string"} {* compiles every time *}
|
||||
```
|
||||
|
||||
Both `string:` and `eval:` resources may be encoded with
|
||||
[`urlencode()`](https://www.php.net/urlencode) or
|
||||
[`base64_encode()`](https://www.php.net/urlencode). This is not necessary
|
||||
for the usual use of `string:` and `eval:`, but is required when using
|
||||
either of them in conjunction with the [`extends resource`](#the-extends-resource).
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->assign('foo','value');
|
||||
$template_string_urlencode = urlencode('display {$foo} here');
|
||||
$template_string_base64 = base64_encode('display {$foo} here');
|
||||
$smarty->display('eval:urlencode:' . $template_string_urlencode); // will decode string using urldecode()
|
||||
$smarty->display('eval:base64:' . $template_string_base64); // will decode string using base64_decode()
|
||||
```
|
||||
|
||||
From within a Smarty template:
|
||||
```smarty
|
||||
{include file="string:urlencode:$template_string_urlencode"} {* will decode string using urldecode() *}
|
||||
{include file="eval:base64:$template_string_base64"} {* will decode string using base64_decode() *}
|
||||
```
|
||||
|
||||
## The extends resource
|
||||
|
||||
The `extends:` resource is used to define child/parent relationships. For details see section of
|
||||
[Template inheritance](inheritance.md).
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Using the extends resource is usually not necessary. If you have a choice, it is normally more flexible and
|
||||
> intuitive to handle inheritance chains from within the templates using the [{extends} tag](inheritance.md).
|
||||
|
||||
When `string:` and `eval:` templates are used, make sure they are properly url or base64 encoded.
|
||||
|
||||
The templates within an inheritance chain are not compiled separately. Only a single compiled template will be generated.
|
||||
(If an `eval:` resource is found within an inheritance chain, its "don't save a compile file" property is superseded by
|
||||
the `extends:` resource.)
|
||||
|
||||
Example:
|
||||
```php
|
||||
<?php
|
||||
$smarty->display('extends:parent.tpl|child.tpl|grandchild.tpl');
|
||||
|
||||
// inheritance from multiple template sources
|
||||
$smarty->display('extends:db:parent.tpl|file:child.tpl|grandchild.tpl|eval:{block name="fooBazVar_"}hello world{/block}');
|
||||
```
|
||||
|
||||
## The stream resource
|
||||
|
||||
Smarty allow you to use [PHP streams](https://www.php.net/manual/en/function.stream-wrapper-register.php)
|
||||
as a template resource. Smarty will first look for a registered template resource. If nothing is
|
||||
found, it will check if a PHP stream is available. If a stream is available, Smarty will use it
|
||||
to fetch the template.
|
||||
|
||||
For example,
|
||||
```php
|
||||
<?php
|
||||
stream_wrapper_register('myresource', MyResourceStream::class);
|
||||
$smarty->display('myresource:bar.tpl');
|
||||
```
|
||||
|
||||
Or, from within a template:
|
||||
```smarty
|
||||
{include file="myresource:bar.tpl"}
|
||||
```
|
||||
|
||||
## Adding your own resource type
|
||||
You can create a class that extends `Smarty\Resource\CustomPlugin` to add your own resource type,
|
||||
for example to load template from a database.
|
||||
|
||||
For example:
|
||||
```php
|
||||
<?php
|
||||
class HelloWorldResource extends Smarty\Resource\CustomPlugin {
|
||||
|
||||
protected function fetch($name, &$source, &$mtime) {
|
||||
$source = '{$x="hello world"}{$x}'; // load your template here based on $name
|
||||
$mtime = time();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ..
|
||||
|
||||
$smarty->registerResource('helloworld', new HelloWorldResource());
|
||||
```
|
||||
|
||||
If a Resource's templates should not be run through the Smarty
|
||||
compiler, the Custom Resource may extend `\Smarty\Resource\UncompiledPlugin`.
|
||||
The Resource Handler must then implement the function
|
||||
`renderUncompiled(\Smarty\Template $_template)`. `$_template` is
|
||||
a reference to the current template and contains all assigned variables
|
||||
which the implementor can access via
|
||||
`$_template->getSmarty()->getTemplateVars()`. These Resources simply echo
|
||||
their rendered content to the output stream. The rendered output will be
|
||||
output-cached if the Smarty instance was configured accordingly. See
|
||||
`src/Resource/PhpPlugin.php` for an example.
|
||||
|
||||
If the Resource's compiled templates should not be cached on disk, the
|
||||
Custom Resource may extend `\Smarty\Resource\RecompiledPlugin`. These Resources
|
||||
are compiled every time they are accessed. This may be an expensive
|
||||
overhead. See `src/Resource/StringEval.php` for an
|
||||
example.
|
||||
|
||||
## Changing the default resource type
|
||||
The default resource type is `file`. If you want to change it, use `Smarty::setDefaultResourceType`.
|
||||
|
||||
The following example will change the default resource type to `mysql`:
|
||||
```php
|
||||
<?php
|
||||
$smarty->setDefaultResourceType('mysql');
|
||||
```
|
119
docs/api/security.md
Normal file
119
docs/api/security.md
Normal file
@ -0,0 +1,119 @@
|
||||
# Security
|
||||
|
||||
Security is good for situations when you have untrusted parties editing
|
||||
the templates, and you want to reduce the risk of system
|
||||
security compromises through the template language.
|
||||
|
||||
The settings of the security policy are defined by overriding public properties of an
|
||||
instance of the \Smarty\Security class. These are the possible settings:
|
||||
|
||||
- `$secure_dir` is an array of template directories that are
|
||||
considered secure. A directory configured using `$smarty->setTemplateDir()` is
|
||||
considered secure implicitly. The default is an empty array.
|
||||
- `$trusted_uri` is an array of regular expressions matching URIs that
|
||||
are considered trusted. This security directive is used by
|
||||
[`{fetch}`](../designers/language-custom-functions/language-function-fetch.md) and
|
||||
[`{html_image}`](../designers/language-custom-functions/language-function-html-image.md). URIs passed to
|
||||
these functions are reduced to `{$PROTOCOL}://{$HOSTNAME}` to allow
|
||||
simple regular expressions (without having to deal with edge cases
|
||||
like authentication-tokens).
|
||||
|
||||
The expression `'#https?://.*smarty.net$#i'` would allow accessing
|
||||
the following URIs:
|
||||
|
||||
- `http://smarty.net/foo`
|
||||
- `http://smarty.net/foo`
|
||||
- `http://www.smarty.net/foo`
|
||||
- `http://smarty.net/foo`
|
||||
- `https://foo.bar.www.smarty.net/foo/bla?blubb=1`
|
||||
|
||||
but deny access to these URIs:
|
||||
|
||||
- `http://smarty.com/foo` (not matching top-level domain \"com\")
|
||||
- `ftp://www.smarty.net/foo` (not matching protocol \"ftp\")
|
||||
- `http://www.smarty.net.otherdomain.com/foo` (not matching end of
|
||||
domain \"smarty.net\")
|
||||
|
||||
- `$static_classes` is an array of classes that are considered
|
||||
trusted. The default is an empty array which allows access to all
|
||||
static classes. To disable access to all static classes set
|
||||
$static_classes = null.
|
||||
|
||||
- `$streams` is an array of streams that are considered trusted and
|
||||
can be used from within template. To disable access to all streams
|
||||
set $streams = null. An empty array ( $streams = [] ) will
|
||||
allow all streams. The default is array('file').
|
||||
|
||||
- `$allowed_modifiers` is an array of (registered / autoloaded)
|
||||
modifiers that should be accessible to the template. If this array
|
||||
is non-empty, only the herein listed modifiers may be used. This is
|
||||
a whitelist.
|
||||
|
||||
- `$disabled_modifiers` is an array of (registered / autoloaded)
|
||||
modifiers that may not be accessible to the template.
|
||||
|
||||
- `$allowed_tags` is a boolean flag which controls if constants can
|
||||
function-, block and filter plugins that should be accessible to the
|
||||
template. If this array is non-empty, only the herein listed
|
||||
modifiers may be used. This is a whitelist.
|
||||
|
||||
- `$disabled_tags` is an array of (registered / autoloaded) function-,
|
||||
block and filter plugins that may not be accessible to the template.
|
||||
|
||||
- `$allow_constants` is a boolean flag which controls if constants can
|
||||
be accessed by the template. The default is "true".
|
||||
|
||||
- `$allow_super_globals` is a boolean flag which controls if the PHP
|
||||
super globals can be accessed by the template. The default is
|
||||
"true".
|
||||
|
||||
If security is enabled, no private methods, functions or properties of
|
||||
static classes or assigned objects can be accessed (beginning with
|
||||
'_') by the template.
|
||||
|
||||
To customize the security policy settings you can extend the
|
||||
\Smarty\Security class or create an instance of it.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
class My_Security_Policy extends \Smarty\Security {
|
||||
public $allow_constants = false;
|
||||
}
|
||||
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->enableSecurity('My_Security_Policy');
|
||||
```
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty();
|
||||
|
||||
$my_security_policy = new \Smarty\Security($smarty);
|
||||
$my_security_policy->allow_constants = false;
|
||||
|
||||
$smarty->enableSecurity($my_security_policy);
|
||||
```
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty();
|
||||
|
||||
// enable default security
|
||||
$smarty->enableSecurity();
|
||||
```
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Most security policy settings are only checked when the template gets
|
||||
> compiled. For that reason you should delete all cached and compiled
|
||||
> template files when you change your security settings.
|
139
docs/api/variables/assigning.md
Normal file
139
docs/api/variables/assigning.md
Normal file
@ -0,0 +1,139 @@
|
||||
# Assigning variables
|
||||
|
||||
Templates start to become really useful once you know how to use variables.
|
||||
|
||||
## Basic assigning
|
||||
Let's revisit the example from the [basics section](../basics.md). The following script assigns a value to
|
||||
the 'companyName' variable and renders the template:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->assign('companyName', 'AC & ME Corp.');
|
||||
|
||||
$smarty->display('footer.tpl');
|
||||
```
|
||||
|
||||
footer.tpl:
|
||||
```smarty
|
||||
<small>Copyright {$companyName|escape}</small>
|
||||
```
|
||||
|
||||
Smarty will apply the [escape modifier](../designers/language-modifiers/language-modifier-escape.md)
|
||||
to the value assigned to the variable
|
||||
`companyName` and replace `{$companyName|escape}` with the result.
|
||||
|
||||
```html
|
||||
<small>Copyright AC & ME Corp.</small>
|
||||
```
|
||||
|
||||
Using `$smarty->assign()` is the most common way of assigning data to templates, but there are several other methods.
|
||||
|
||||
## Appending data to an existing variable
|
||||
Using `append()`, you can add data to an existing variable, usually an array.
|
||||
|
||||
If you append to a string value, it is converted to an array value and
|
||||
then appended to. You can explicitly pass name/value pairs, or
|
||||
associative arrays containing the name/value pairs. If you pass the
|
||||
optional third parameter of TRUE, the value will be merged with the
|
||||
current array instead of appended.
|
||||
|
||||
Examples:
|
||||
|
||||
```php
|
||||
<?php
|
||||
// This is effectively the same as assign()
|
||||
$smarty->append('foo', 'Fred');
|
||||
// After this line, foo will now be seen as an array in the template
|
||||
$smarty->append('foo', 'Albert');
|
||||
|
||||
$array = [1 => 'one', 2 => 'two'];
|
||||
$smarty->append('X', $array);
|
||||
$array2 = [3 => 'three', 4 => 'four'];
|
||||
// The following line will add a second element to the X array
|
||||
$smarty->append('X', $array2);
|
||||
|
||||
// passing an associative array
|
||||
$smarty->append(['city' => 'Lincoln', 'state' => 'Nebraska']);
|
||||
```
|
||||
|
||||
## Assigning to template objects
|
||||
When you use a template objects, as explained in [rendering a template](../rendering.md#creating-a-template-object),
|
||||
you can assign data to the template objects directly instead of assigning it to Smarty. This way, you can use different
|
||||
sets of data for different templates.
|
||||
|
||||
For example:
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$tplBlue = $smarty->createTemplate('blue.tpl');
|
||||
$tplBlue->assign('name', 'The one');
|
||||
$tplBlue->display();
|
||||
|
||||
$tplRed = $smarty->createTemplate('red.tpl');
|
||||
$tplRed->assign('name', 'Neo');
|
||||
$tplRed->display();
|
||||
```
|
||||
|
||||
## Using data objects
|
||||
For more complex use cases, Smarty supports the concept of data objects.
|
||||
Data objects are containers to hold data. Data objects can be attached to templates when creating them.
|
||||
This allows for fine-grained re-use of data.
|
||||
|
||||
For example:
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// create a data object
|
||||
$data = $smarty->createData();
|
||||
|
||||
// assign variable to the data object
|
||||
$data->assign('name', 'Neo');
|
||||
|
||||
// create template object which will use variables from the data object
|
||||
$tpl = $smarty->createTemplate('index.tpl', $data);
|
||||
|
||||
// display the template
|
||||
$tpl->display();
|
||||
```
|
||||
|
||||
## Clearing assigned data
|
||||
When re-using templates, you may need to clear data assigned in a previous run. Use `clearAllAssign()` to
|
||||
clear the values of all assigned variables on data objects, template objects or the Smarty object.
|
||||
|
||||
Examples:
|
||||
```php
|
||||
<?php
|
||||
// assigning data to the Smarty object
|
||||
$smarty->assign('Name', 'Fred');
|
||||
// ...
|
||||
$smarty->clearAllAssign();
|
||||
|
||||
// using a data object
|
||||
$data = $smarty->createData();
|
||||
$data->assign('name', 'Neo');
|
||||
// ...
|
||||
$data->clearAllAssign();
|
||||
|
||||
// using a template
|
||||
$tplBlue = $smarty->createTemplate('blue.tpl');
|
||||
$tplBlue->assign('name', 'The one');
|
||||
// ...
|
||||
$tplBlue->clearAllAssign();
|
||||
```
|
||||
|
||||
Note that there it's only useful to clear assigned data if you:
|
||||
|
||||
1. repeatedly re-use templates, and
|
||||
2. the variables used may change on each repetition
|
||||
|
||||
If your script simply runs once and then ends, or you always assign the same variables, clearing assigned data
|
||||
is of no use.
|
89
docs/api/variables/config-files.md
Normal file
89
docs/api/variables/config-files.md
Normal file
@ -0,0 +1,89 @@
|
||||
# Loading data from config files
|
||||
|
||||
Instead of [assigning data to templates from PHP](assigning.md), you can also
|
||||
use a config file.
|
||||
|
||||
## Example config file
|
||||
Config files are best suited to manage template settings
|
||||
from one file. One example is a multi-language application.
|
||||
Instead of writing multiple templates to support different languages,
|
||||
you can write a single template file and load your language dependent strings
|
||||
from config files.
|
||||
|
||||
Example `lang.en.ini`:
|
||||
```ini
|
||||
# global variables
|
||||
pageTitle = "Main Menu"
|
||||
|
||||
[Customer]
|
||||
pageTitle = "Customer Info"
|
||||
|
||||
[Login]
|
||||
pageTitle = "Login"
|
||||
focus = "username"
|
||||
Intro = """This is a value that spans more
|
||||
than one line. you must enclose
|
||||
it in triple quotes."""
|
||||
|
||||
```
|
||||
|
||||
Values of [config file variables](./language-variables/language-config-variables.md) can be in
|
||||
quotes, but not necessary. You can use either single or double quotes.
|
||||
If you have a value that spans more than one line, enclose the entire
|
||||
value with triple quotes \("""\). You can put comments into config
|
||||
files by any syntax that is not a valid config file syntax. We recommend
|
||||
using a `#` (hash) at the beginning of the line.
|
||||
|
||||
The example config file above has two sections. Section names are
|
||||
enclosed in \[brackets\]. Section names can be arbitrary strings not
|
||||
containing `[` or `]` symbols. The variable at the top is a global
|
||||
variable. Global variables are always
|
||||
loaded from the config file. If a particular section is loaded, then the
|
||||
global variables and the variables from that section are also loaded. If
|
||||
a variable exists both as a global and in a section, the section
|
||||
variable is used.
|
||||
|
||||
## Loading a config file
|
||||
|
||||
Config files are loaded into templates with the built-in template
|
||||
function [`{config_load}`](../../designers/language-builtin-functions/language-function-config-load.md) or by calling
|
||||
`configLoad()` from PHP:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->configLoad('lang.en.ini');
|
||||
```
|
||||
|
||||
Load a specific section with:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$smarty->configLoad('lang.en.ini', 'Customer');
|
||||
```
|
||||
|
||||
Note that the global section will always be loaded.
|
||||
|
||||
## Retrieving config variables in PHP
|
||||
|
||||
|
||||
## Loading from a resource
|
||||
Config files (or resources) are loaded by the same resource facilities
|
||||
as templates. That means that a config file can also be loaded from a db. See [resources](../resources.md)
|
||||
for more information.
|
||||
|
||||
## Config overwrite
|
||||
If you name two variables the same within a section,
|
||||
the last one will be used unless you call:
|
||||
```php
|
||||
<?php
|
||||
$smarty->setConfigOverwrite(false);
|
||||
```
|
||||
When config overwrite is disabled, Smarty will create arrays of config file variables when it encounters
|
||||
multiple entries with the same name.
|
||||
|
||||
See also [`{config_load}`](./language-builtin-functions/language-function-config-load.md),
|
||||
[`$config_overwrite`](../programmers/api-variables/variable-config-overwrite.md),
|
||||
[`$default_config_handler_func`](../programmers/api-variables/variable-default-config-handler-func.md),
|
||||
[`getConfigVars()`](../programmers/api-functions/api-get-config-vars.md),
|
||||
[`clearConfig()`](../programmers/api-functions/api-clear-config.md) and
|
||||
[`configLoad()`](../programmers/api-functions/api-config-load.md)
|
106
docs/api/variables/objects.md
Normal file
106
docs/api/variables/objects.md
Normal file
@ -0,0 +1,106 @@
|
||||
# Objects
|
||||
|
||||
Smarty allows access to PHP [objects](https://www.php.net/object) through
|
||||
the templates.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> When you assign/register objects to templates, be sure that all
|
||||
> properties and methods accessed from the template are for presentation
|
||||
> purposes only. It is very easy to inject application logic through
|
||||
> objects, and this leads to poor designs that are difficult to manage.
|
||||
> See the Best Practices section of the Smarty website.
|
||||
|
||||
There are two ways to access them.
|
||||
|
||||
## Assign the object
|
||||
You can assign objects to a template and access them much like any other assigned variable.
|
||||
|
||||
Example:
|
||||
```php
|
||||
<?php
|
||||
// the object
|
||||
|
||||
class My_Object {
|
||||
public function meth1($params, $smarty_obj) {
|
||||
return 'this is my meth1';
|
||||
}
|
||||
}
|
||||
|
||||
// We can also assign objects. assign_by_ref when possible.
|
||||
$smarty->assign('myobj', new My_Object());
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
And here's how to access your object in `index.tpl`:
|
||||
|
||||
```smarty
|
||||
{$myobj->meth1('foo',$bar)}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Register the object
|
||||
Registerd objects use a different template syntax. Also, a registered object
|
||||
can be restricted to certain methods or
|
||||
properties. However, **a registered object cannot be looped over or
|
||||
assigned in arrays of objects**, etc.
|
||||
|
||||
If security is enabled, no private methods or functions can be accessed
|
||||
(beginning with '_'). If a method and property of the same name exist,
|
||||
the method will be used.
|
||||
|
||||
You can restrict the methods and properties that can be accessed by
|
||||
listing them in an array as the third registration parameter.
|
||||
|
||||
By default, parameters passed to objects through the templates are
|
||||
passed the same way [custom functions](../../designers/language-custom-functions/index.md) get
|
||||
them. An associative array is passed as the first parameter, and the
|
||||
smarty object as the second. If you want the parameters passed one at a
|
||||
time for each argument like traditional object parameter passing, set
|
||||
the fourth registration parameter to FALSE.
|
||||
|
||||
The optional fifth parameter has only effect with `format` being TRUE
|
||||
and contains a list of methods that should be treated as blocks. That
|
||||
means these methods have a closing tag in the template
|
||||
(`{foobar->meth2}...{/foobar->meth2}`) and the parameters to the methods
|
||||
have the same synopsis as the parameters for
|
||||
[`block tags`](../extending/block-tags.md): They get the four
|
||||
parameters `$params`, `$content`, `$smarty` and `&$repeat` and they also
|
||||
behave like block tags.
|
||||
|
||||
```php
|
||||
<?php
|
||||
// the object
|
||||
|
||||
class My_Object {
|
||||
function meth1($params, $smarty_obj) {
|
||||
return 'this is my meth1';
|
||||
}
|
||||
}
|
||||
|
||||
$myobj = new My_Object;
|
||||
|
||||
// registering the object
|
||||
$smarty->registerObject('foobar', $myobj);
|
||||
|
||||
// if we want to restrict access to certain methods or properties, list them
|
||||
$smarty->registerObject('foobar', $myobj, array('meth1','meth2','prop1'));
|
||||
|
||||
// if you want to use the traditional object parameter format, pass a boolean of false
|
||||
$smarty->registerObject('foobar', $myobj, null, false);
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
```
|
||||
|
||||
And here's how to access your objects in `index.tpl`:
|
||||
|
||||
```smarty
|
||||
{* access our registered object *}
|
||||
{foobar->meth1 p1='foo' p2=$bar}
|
||||
|
||||
{* you can also assign the output *}
|
||||
{foobar->meth1 p1='foo' p2=$bar assign='output'}
|
||||
the output was {$output}
|
||||
```
|
39
docs/api/variables/static-class-methods.md
Normal file
39
docs/api/variables/static-class-methods.md
Normal file
@ -0,0 +1,39 @@
|
||||
# Static Classes
|
||||
|
||||
You can directly access static classes. The syntax is roughly the same as in
|
||||
PHP.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Direct access to PHP classes is not recommended. This ties the
|
||||
> underlying application code structure directly to the presentation,
|
||||
> and also complicates template syntax. It is recommended to register
|
||||
> plugins which insulate templates from PHP classes/objects. Use at your
|
||||
> own discretion.
|
||||
|
||||
## Examples
|
||||
|
||||
**class constant BAR**
|
||||
```smarty
|
||||
{assign var=foo value=myclass::BAR}
|
||||
```
|
||||
|
||||
**method result**
|
||||
```smarty
|
||||
{assign var=foo value=myclass::method()}
|
||||
```
|
||||
|
||||
**method chaining**
|
||||
```smarty
|
||||
{assign var=foo value=myclass::method1()->method2}
|
||||
```
|
||||
|
||||
**property bar of class myclass**
|
||||
```smarty
|
||||
{assign var=foo value=myclass::$bar}
|
||||
```
|
||||
|
||||
**using Smarty variable bar as class name**
|
||||
```smarty
|
||||
{assign var=foo value=$bar::method}
|
||||
```
|
13
docs/api/variables/streams.md
Normal file
13
docs/api/variables/streams.md
Normal file
@ -0,0 +1,13 @@
|
||||
# Streams
|
||||
|
||||
You can also use streams to call variables. *{$foo:bar}* will use the
|
||||
*foo://bar* stream to get the template variable.
|
||||
|
||||
Using a PHP stream for a template variable resource from within a
|
||||
template.
|
||||
|
||||
```smarty
|
||||
{$foo:bar}
|
||||
```
|
||||
|
||||
See also [`Template Resources`](../resources.md)
|
@ -209,8 +209,7 @@ fetching the data up front?
|
||||
You can do this by writing a custom plugin for fetching the content and
|
||||
assigning it to a template variable.
|
||||
|
||||
`function.load_ticker.php` - drop file in
|
||||
[`$plugins directory`](../programmers/api-variables/variable-plugins-dir.md)
|
||||
`function.load_ticker.php`
|
||||
|
||||
```php
|
||||
|
||||
|
@ -10,8 +10,7 @@ of the console.
|
||||
|
||||
Set [`$debugging`](../programmers/api-variables/variable-debugging.md) to TRUE in Smarty, and if needed
|
||||
set [`$debug_tpl`](../programmers/api-variables/variable-debug-template.md) to the template resource
|
||||
path to `debug.tpl` (this is in [`SMARTY_DIR`](../programmers/smarty-constants.md) by
|
||||
default). When you load the page, a Javascript console window will pop
|
||||
path to `debug.tpl`. When you load the page, a Javascript console window will pop
|
||||
up and give you the names of all the included templates and assigned
|
||||
variables for the current page.
|
||||
|
||||
|
@ -26,8 +26,8 @@ The basis components of the Smarty syntax are:
|
||||
|
||||
- [Comments](language-syntax-comments.md)
|
||||
- [Variables](language-syntax-variables.md)
|
||||
- [Operators](language-syntax-operators.md)
|
||||
- [Functions](language-syntax-functions.md)
|
||||
- [Attributes](language-syntax-attributes.md)
|
||||
- [Quotes](language-syntax-quotes.md)
|
||||
- [Math](language-math.md)
|
||||
- [Escaping](language-escaping.md)
|
||||
|
@ -69,7 +69,7 @@ Where the template is:
|
||||
|
||||
```smarty
|
||||
Welcome <!--{$name}--> to Smarty
|
||||
<script language="javascript">
|
||||
<script>
|
||||
var foo = <!--{$foo}-->;
|
||||
function dosomething() {
|
||||
alert("foo is " + foo);
|
||||
|
@ -1,28 +0,0 @@
|
||||
# Math
|
||||
|
||||
Math can be applied directly to variable values.
|
||||
|
||||
## Examples
|
||||
```smarty
|
||||
{$foo+1}
|
||||
|
||||
{$foo*$bar}
|
||||
|
||||
{* some more complicated examples *}
|
||||
|
||||
{$foo->bar-$bar[1]*$baz->foo->bar()-3*7}
|
||||
|
||||
{if ($foo+$bar.test%$baz*134232+10+$b+10)}
|
||||
|
||||
{$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"}
|
||||
|
||||
{assign var="foo" value="`$foo+$bar`"}
|
||||
```
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Although Smarty can handle some very complex expressions and syntax,
|
||||
> it is a good rule of thumb to keep the template syntax minimal and
|
||||
> focused on presentation. If you find your template syntax getting too
|
||||
> complex, it may be a good idea to move the bits that do not deal
|
||||
> explicitly with presentation to PHP by way of plugins or modifiers.
|
@ -11,7 +11,6 @@ within delimiters like so: `{funcname attr1="val1" attr2="val2"}`.
|
||||
{config_load file="colors.conf"}
|
||||
|
||||
{include file="header.tpl"}
|
||||
{insert file="banner_ads.tpl" title="My Site"}
|
||||
|
||||
{if $logged_in}
|
||||
Welcome, <span style="color:{#fontColor#}">{$name}!</span>
|
||||
|
@ -0,0 +1,64 @@
|
||||
# Operators
|
||||
|
||||
## Basic
|
||||
|
||||
Various basic operators can be applied directly to variable values.
|
||||
|
||||
## Examples
|
||||
```smarty
|
||||
{$foo + 1}
|
||||
|
||||
{$foo * $bar}
|
||||
|
||||
{$foo->bar - $bar[1] * $baz->foo->bar() -3 * 7}
|
||||
|
||||
{if ($foo + $bar.test % $baz * 134232 + 10 + $b + 10)}
|
||||
...
|
||||
{/if}
|
||||
|
||||
{$foo = $foo + $bar}
|
||||
```
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Although Smarty can handle some very complex expressions and syntax,
|
||||
> it is a good rule of thumb to keep the template syntax minimal and
|
||||
> focused on presentation. If you find your template syntax getting too
|
||||
> complex, it may be a good idea to move the bits that do not deal
|
||||
> explicitly with presentation to PHP by way of plugins or modifiers.
|
||||
|
||||
## Ternary
|
||||
You can use the `?:` (or ternary) operator to test one expression and present the value
|
||||
of the second or third expression, based on the result of the test.
|
||||
|
||||
In other words:
|
||||
```smarty
|
||||
{$test ? "OK" : "FAIL"}
|
||||
```
|
||||
will result in OK if `$test` is set to true, and in FAIL otherwise.
|
||||
|
||||
There is also a shorthand `?:` operator:
|
||||
```smarty
|
||||
{$myVar ?: "empty"}
|
||||
```
|
||||
will result in 'empty' if `$myVar` is not set or set to something that evaluates to false, such as an empty string.
|
||||
If `$myVar` is set to something that evaluates to true, the value of `$myVar` is returned. So, the following will
|
||||
return 'hello':
|
||||
```smarty
|
||||
{$myVar="hello"}
|
||||
{$myVar ?: "empty"}
|
||||
```
|
||||
|
||||
## Testing for null
|
||||
If "something that evaluates to false" is to broad a test for you, you can use the `??` (or null coalescing) operator
|
||||
to trigger only if the tested value is undefined or set to null.
|
||||
```smarty
|
||||
{$myVar ?? "empty"}
|
||||
```
|
||||
will result in 'empty' if `$myVar` is not set or set to null.
|
||||
If `$myVar` is set to something that evaluates to anything else, the value of `$myVar` is returned. So, the following will
|
||||
return an empty string (''):
|
||||
```smarty
|
||||
{$myVar=""}
|
||||
{$myVar ?: "this is not shown"}
|
||||
```
|
0
docs/designers/language-builtin-functions.md
Normal file
0
docs/designers/language-builtin-functions.md
Normal file
@ -134,7 +134,6 @@ echo $smarty->getTemplateVars('foo');
|
||||
|
||||
The following functions can also *optionally* assign template variables: [`{capture}`](#language.function.capture),
|
||||
[`{include}`](#language.function.include),
|
||||
[`{insert}`](#language.function.insert),
|
||||
[`{counter}`](#language.function.counter),
|
||||
[`{cycle}`](#language.function.cycle),
|
||||
[`{eval}`](#language.function.eval),
|
||||
|
@ -27,12 +27,6 @@ is the value passed in the `name` attribute. If you do not supply the
|
||||
|---------|-----------------------------------------|
|
||||
| nocache | Disables caching of this captured block |
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Be careful when capturing [`{insert}`](#language.function.insert)
|
||||
> output. If you have [`$caching`](#caching) enabled and you have
|
||||
> [`{insert}`](#language.function.insert) commands that you expect to
|
||||
> run within cached content, do not capture this content.
|
||||
|
||||
## Examples
|
||||
|
||||
|
@ -166,7 +166,7 @@ looping over a PHP iterator instead of an array().
|
||||
|
||||
```php
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty;
|
||||
|
||||
|
@ -7,10 +7,6 @@ template engine. Every `{if}` must be paired with a matching `{/if}`.
|
||||
functions are recognized, such as *\|\|*, *or*, *&&*, *and*,
|
||||
*is_array()*, etc.
|
||||
|
||||
If security is enabled, only PHP functions from `$php_functions` property
|
||||
of the security policy are allowed. See the
|
||||
[Security](../../programmers/advanced-features/advanced-features-security.md) section for details.
|
||||
|
||||
The following is a list of recognized qualifiers, which must be
|
||||
separated from surrounding elements by spaces. Note that items listed in
|
||||
\[brackets\] are optional. PHP equivalents are shown where applicable.
|
||||
|
@ -183,5 +183,5 @@ current template.
|
||||
{include file="$style_dir/$module.$view.tpl"}
|
||||
```
|
||||
|
||||
See also [`{insert}`](./language-function-insert.md), [template resources](../../programmers/resources.md) and
|
||||
See also [template resources](../../programmers/resources.md) and
|
||||
[componentized templates](../../appendixes/tips.md#componentized-templates).
|
||||
|
@ -1,86 +0,0 @@
|
||||
# {insert}
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> `{insert}` tags are deprecated from Smarty, and should not be used.
|
||||
> Put your PHP logic in PHP scripts or plugin functions instead.
|
||||
> As of Smarty 3.1 the `{insert}` tags are only available from
|
||||
> [SmartyBC](#bc).
|
||||
|
||||
`{insert}` tags work much like [`{include}`](./language-function-include.md)
|
||||
tags, except that `{insert}` tags are NOT cached when template
|
||||
[caching](../../programmers/caching.md) is enabled. They will be executed on every
|
||||
invocation of the template.
|
||||
|
||||
| Attribute Name | Required | Description |
|
||||
|----------------|----------|----------------------------------------------------------------------------------|
|
||||
| name | Yes | The name of the insert function (insert_`name`) or insert plugin |
|
||||
| assign | No | The name of the template variable the output will be assigned to |
|
||||
| script | No | The name of the php script that is included before the insert function is called |
|
||||
| \[var \...\] | No | variable to pass to insert function |
|
||||
|
||||
## Examples
|
||||
|
||||
Let's say you have a template with a banner slot at the top of the
|
||||
page. The banner can contain any mixture of HTML, images, flash, etc. so
|
||||
we can't just use a static link here, and we don't want this contents
|
||||
cached with the page. In comes the {insert} tag: the template knows
|
||||
\#banner\_location\_id\# and \#site\_id\# values (gathered from a
|
||||
[config file](../config-files.md)), and needs to call a function to get the
|
||||
banner contents.
|
||||
|
||||
```smarty
|
||||
{* example of fetching a banner *}
|
||||
{insert name="getBanner" lid=#banner_location_id# sid=#site_id#}
|
||||
{insert "getBanner" lid=#banner_location_id# sid=#site_id#} {* short-hand *}
|
||||
```
|
||||
|
||||
In this example, we are using the name "getBanner" and passing the
|
||||
parameters \#banner\_location\_id\# and \#site\_id\#. Smarty will look
|
||||
for a function named insert\_getBanner() in your PHP application,
|
||||
passing the values of \#banner\_location\_id\# and \#site\_id\# as the
|
||||
first argument in an associative array. All {insert} function names in
|
||||
your application must be prepended with "insert_" to remedy possible
|
||||
function name-space conflicts. Your insert\_getBanner() function should
|
||||
do something with the passed values and return the results. These
|
||||
results are then displayed in the template in place of the {insert} tag.
|
||||
In this example, Smarty would call this function:
|
||||
insert_getBanner(array("lid" => "12345","sid" => "67890"));
|
||||
and display the returned results in place of the {insert} tag.
|
||||
|
||||
- If you supply the `assign` attribute, the output of the `{insert}`
|
||||
tag will be assigned to this template variable instead of being
|
||||
output to the template.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Assigning the output to a template variable isn't too useful with
|
||||
> [caching](../../programmers/api-variables/variable-caching.md) enabled.
|
||||
|
||||
- If you supply the `script` attribute, this php script will be
|
||||
included (only once) before the `{insert}` function is executed.
|
||||
This is the case where the insert function may not exist yet, and a
|
||||
php script must be included first to make it work.
|
||||
|
||||
The path can be either absolute, or relative to
|
||||
[`$trusted_dir`](../../programmers/api-variables/variable-trusted-dir.md). If security is enabled,
|
||||
then the script must be located in the `$trusted_dir` path of the
|
||||
security policy. See the [Security](../../programmers/advanced-features/advanced-features-security.md)
|
||||
section for details.
|
||||
|
||||
The Smarty object is passed as the second argument. This way you can
|
||||
reference and modify information in the Smarty object from within the
|
||||
`{insert}` function.
|
||||
|
||||
If no PHP script can be found Smarty is looking for a corresponding
|
||||
insert plugin.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> It is possible to have portions of the template not cached. If you
|
||||
> have [caching](../../programmers/api-variables/variable-caching.md) turned on, `{insert}` tags will not be
|
||||
> cached. They will run dynamically every time the page is created, even
|
||||
> within cached pages. This works good for things like banners, polls,
|
||||
> live weather, search results, user feedback areas, etc.
|
||||
|
||||
See also [`{include}`](./language-function-include.md)
|
||||
|
@ -17,4 +17,4 @@ Today's date is
|
||||
|
||||
The above code will output the current date on a cached page.
|
||||
|
||||
See also the [caching section](../../programmers/caching.md).
|
||||
See also the [caching section](../../api/caching/basics.md).
|
||||
|
@ -34,7 +34,7 @@ spiders to lift email addresses off of a site.
|
||||
<a href="mailto:me@example.com" >send me some mail</a>
|
||||
|
||||
{mailto address="me@example.com" encode="javascript"}
|
||||
<script type="text/javascript" language="javascript">
|
||||
<script>
|
||||
eval(unescape('%64%6f% ... snipped ...%61%3e%27%29%3b'))
|
||||
</script>
|
||||
|
||||
@ -51,7 +51,7 @@ spiders to lift email addresses off of a site.
|
||||
<a href="mailto:me@example.com" class="email">me@example.com</a>
|
||||
|
||||
{mailto address="me@example.com" encode="javascript_charcode"}
|
||||
<script type="text/javascript" language="javascript">
|
||||
<script>
|
||||
{document.write(String.fromCharCode(60,97, ... snipped ....60,47,97,62))}
|
||||
</script>
|
||||
```
|
||||
|
@ -69,7 +69,7 @@ These parameters follow the modifier name and are separated by a `:`
|
||||
<select name="name_id">
|
||||
{html_options output=$my_array|upper|truncate:20}
|
||||
</select>
|
||||
```
|
||||
```
|
||||
|
||||
- Modifiers can be applied to any type of variables, including arrays
|
||||
and objects.
|
||||
@ -96,26 +96,9 @@ These parameters follow the modifier name and are separated by a `:`
|
||||
> gives 9. To get the old result use parentheses like
|
||||
> `{(8+2)|count_characters}`.
|
||||
|
||||
- Modifiers are autoloaded from the
|
||||
[`$plugins_dir`](../../programmers/api-variables/variable-plugins-dir.md) or can be registered
|
||||
explicitly with the [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md)
|
||||
function. The later is useful for sharing a function between php
|
||||
scripts and smarty templates.
|
||||
|
||||
- All php-functions can be used as modifiers implicitly, as
|
||||
demonstrated in the example above. However, using php-functions as
|
||||
modifiers has two little pitfalls:
|
||||
|
||||
- First - sometimes the order of the function-parameters is not
|
||||
the desirable one. Formatting `$foo` with
|
||||
`{"%2.f"|sprintf:$foo}` actually works, but asks for the more
|
||||
intuitive, like `{$foo|string_format:"%2.f"}` that is provided
|
||||
by the Smarty distribution.
|
||||
|
||||
- Secondly - if security is enabled, all php-functions that are to
|
||||
be used as modifiers have to be declared trusted in the
|
||||
`$modifiers` property of the security policy. See the
|
||||
[Security](../../programmers/advanced-features/advanced-features-security.md) section for details.
|
||||
- Custom modifiers can be registered
|
||||
with the [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md)
|
||||
function.
|
||||
|
||||
See also [`registerPlugin()`](../../programmers/api-functions/api-register-plugin.md), [combining
|
||||
modifiers](../language-combining-modifiers.md). and [extending smarty with
|
||||
|
@ -16,5 +16,5 @@ modifier](language-modifier-to-charset.md).
|
||||
> modifier should only be used in cases where the application cannot
|
||||
> anticipate that a certain string is required in another encoding.
|
||||
|
||||
See also [Charset Encoding](../../programmers/charset.md), [to_charset
|
||||
See also [Configuring Smarty](../../api/configuring.md), [to_charset
|
||||
modifier](language-modifier-to-charset.md).
|
||||
|
@ -16,5 +16,5 @@ modifier](#language.modifier.from_charset).
|
||||
> modifier should only be used in cases where the application cannot
|
||||
> anticipate that a certain string is required in another encoding.
|
||||
|
||||
See also [Charset Encoding](../../programmers/charset.md), [from_charset
|
||||
See also [Configuring Smarty](../../api/configuring.md), [from_charset
|
||||
modifier](language-modifier-from-charset.md).
|
||||
|
@ -7,7 +7,7 @@ Variables assigned from PHP are referenced by preceding them with a dollar
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->assign('firstname', 'Doug');
|
||||
|
@ -66,8 +66,7 @@ difference.
|
||||
|
||||
## {$smarty.const}
|
||||
|
||||
You can access PHP constant values directly. See also [smarty
|
||||
constants](../../programmers/smarty-constants.md).
|
||||
You can access PHP constant values directly.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
@ -1,7 +1,7 @@
|
||||
# Getting started
|
||||
|
||||
## Requirements
|
||||
Smarty can be run with PHP 7.1 to PHP 8.2.
|
||||
Smarty can be run with PHP 7.2 to PHP 8.2.
|
||||
|
||||
## Installation
|
||||
Smarty can be installed with [Composer](https://getcomposer.org/).
|
||||
@ -26,22 +26,21 @@ Here's how you create an instance of Smarty in your PHP scripts:
|
||||
<?php
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
```
|
||||
|
||||
Now that the library files are in place, it's time to set up the Smarty
|
||||
directories for your application.
|
||||
|
||||
Smarty requires four directories which are by default named
|
||||
[`templates`](./programmers/api-variables/variable-template-dir.md),
|
||||
[`configs`](./programmers/api-variables/variable-config-dir.md),
|
||||
[`templates_c`](./programmers/api-variables/variable-compile-dir.md)
|
||||
and
|
||||
[`cache`](./programmers/api-variables/variable-cache-dir.md)
|
||||
relative to the current working directory.
|
||||
Smarty requires four directories which are by default named `templates`, `configs`, `templates_c` and `cache`
|
||||
relative to the current working directory.
|
||||
|
||||
The defaults can be changed as follows:
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
$smarty->setTemplateDir('/some/template/dir');
|
||||
$smarty->setConfigDir('/some/config/dir');
|
||||
@ -70,6 +69,8 @@ You can verify if your system has the correct access rights for
|
||||
these directories with [`testInstall()`](./programmers/api-functions/api-test-install.md):
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
$smarty->setTemplateDir('/some/template/dir');
|
||||
$smarty->setConfigDir('/some/config/dir');
|
||||
@ -103,6 +104,7 @@ Now lets edit our php file. We'll create an instance of Smarty,
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
|
||||
$smarty->setTemplateDir('/web/www.example.com/guestbook/templates/');
|
||||
@ -140,7 +142,9 @@ the same vars, etc., we can do that in one place.
|
||||
```php
|
||||
<?php
|
||||
|
||||
class Smarty_GuestBook extends Smarty {
|
||||
use Smarty\Smarty;
|
||||
|
||||
class My_GuestBook extends Smarty {
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@ -158,7 +162,7 @@ class Smarty_GuestBook extends Smarty {
|
||||
}
|
||||
```
|
||||
|
||||
Now, we can use `Smarty_GuestBook` instead of `Smarty` in our scripts:
|
||||
Now, we can use `My_GuestBook` instead of `Smarty` in our scripts:
|
||||
```php
|
||||
<?php
|
||||
$smarty = new Smarty_GuestBook();
|
||||
|
BIN
docs/img/favicon.ico
Normal file
BIN
docs/img/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 7.6 KiB |
@ -1,8 +1,8 @@
|
||||
# Smarty 4 Documentation
|
||||
# Smarty Documentation
|
||||
Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.
|
||||
|
||||
It allows you to write **templates**, using **variables**, **modifiers**, **functions** and **comments**, like this:
|
||||
```html
|
||||
```smarty
|
||||
<h1>{$title|escape}</h1>
|
||||
|
||||
<p>
|
||||
@ -20,31 +20,11 @@ and 480 for $height, the result is:
|
||||
</p>
|
||||
```
|
||||
|
||||
## Introduction
|
||||
## Getting Started
|
||||
- [Getting Started](./getting-started.md)
|
||||
- [Philosophy](./philosophy.md) - or "Why do I need a template engine?"
|
||||
- [Features](./features.md) - or "Why do I want Smarty?"
|
||||
- [Getting Started](./getting-started.md)
|
||||
|
||||
## Smarty for template designers
|
||||
- [Basic Syntax](designers/language-basic-syntax/index.md)
|
||||
- [Variables](designers/language-variables/index.md)
|
||||
- [Variable Modifiers](designers/language-modifiers/index.md)
|
||||
- [Combining Modifiers](./designers/language-combining-modifiers.md)
|
||||
- [Built-in Functions](designers/language-builtin-functions/index.md)
|
||||
- [Custom Functions](designers/language-custom-functions/index.md)
|
||||
- [Config Files](./designers/config-files.md)
|
||||
- [Debugging Console](./designers/chapter-debugging-console.md)
|
||||
|
||||
## Smarty for php developers
|
||||
- [Charset Encoding](./programmers/charset.md)
|
||||
- [Constants](./programmers/smarty-constants.md)
|
||||
- [Smarty Class Variables](./programmers/api-variables.md)
|
||||
- [Smarty Class Methods](./programmers/api-functions.md)
|
||||
- [Caching](./programmers/caching.md)
|
||||
- [Resources](./programmers/resources.md)
|
||||
- [Advanced Features](./programmers/advanced-features.md)
|
||||
- [Extending Smarty With Plugins](./programmers/plugins.md)
|
||||
|
||||
## Other
|
||||
## Help
|
||||
- [Some random tips & tricks](./appendixes/tips.md)
|
||||
- [Troubleshooting](./appendixes/troubleshooting.md)
|
||||
|
@ -8,7 +8,7 @@ presentation. This is best described in a situation where the
|
||||
application programmer and the template designer play different roles,
|
||||
or in most cases are not the same person.
|
||||
|
||||
For example, let\'s say you are creating a web page that is displaying a
|
||||
For example, let's say you are creating a web page that is displaying a
|
||||
newspaper article.
|
||||
|
||||
- The article `$headline`, `$tagline`, `$author` and `$body` are
|
||||
|
@ -1,14 +0,0 @@
|
||||
Advanced Features {#advanced.features}
|
||||
=================
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [Security](./advanced-features/advanced-features-security.md)
|
||||
- [Changing settings by template](./advanced-features/advanced-features-template-settings.md)
|
||||
- [Template Inheritance](./advanced-features/advanced-features-template-inheritance.md)
|
||||
- [Streams](./advanced-features/advanced-features-streams.md)
|
||||
- [Objects](./advanced-features/advanced-features-objects.md)
|
||||
- [Static Classes](./advanced-features/advanced-features-static-classes.md)
|
||||
- [Prefilters](./advanced-features/advanced-features-prefilters.md)
|
||||
- [Postfilters](./advanced-features/advanced-features-postfilters.md)
|
||||
- [Output Filters](./advanced-features/advanced-features-outputfilters.md)
|
@ -1,99 +0,0 @@
|
||||
Objects {#advanced.features.objects}
|
||||
=======
|
||||
|
||||
Smarty allows access to PHP [objects](https://www.php.net/object) through
|
||||
the templates.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> When you assign/register objects to templates, be sure that all
|
||||
> properties and methods accessed from the template are for presentation
|
||||
> purposes only. It is very easy to inject application logic through
|
||||
> objects, and this leads to poor designs that are difficult to manage.
|
||||
> See the Best Practices section of the Smarty website.
|
||||
|
||||
There are two ways to access them.
|
||||
|
||||
- One way is to [register objects](#api.register.object) to the
|
||||
template, then use access them via syntax similar to [custom
|
||||
functions](#language.custom.functions).
|
||||
|
||||
- The other way is to [`assign()`](#api.assign) objects to the
|
||||
templates and access them much like any other assigned variable.
|
||||
|
||||
The first method has a much nicer template syntax. It is also more
|
||||
secure, as a registered object can be restricted to certain methods or
|
||||
properties. However, **a registered object cannot be looped over or
|
||||
assigned in arrays of objects**, etc. The method you choose will be
|
||||
determined by your needs, but use the first method whenever possible to
|
||||
keep template syntax to a minimum.
|
||||
|
||||
If security is enabled, no private methods or functions can be accessed
|
||||
(beginning with \'\_\'). If a method and property of the same name exist,
|
||||
the method will be used.
|
||||
|
||||
You can restrict the methods and properties that can be accessed by
|
||||
listing them in an array as the third registration parameter.
|
||||
|
||||
By default, parameters passed to objects through the templates are
|
||||
passed the same way [custom functions](#language.custom.functions) get
|
||||
them. An associative array is passed as the first parameter, and the
|
||||
smarty object as the second. If you want the parameters passed one at a
|
||||
time for each argument like traditional object parameter passing, set
|
||||
the fourth registration parameter to FALSE.
|
||||
|
||||
The optional fifth parameter has only effect with `format` being TRUE
|
||||
and contains a list of methods that should be treated as blocks. That
|
||||
means these methods have a closing tag in the template
|
||||
(`{foobar->meth2}...{/foobar->meth2}`) and the parameters to the methods
|
||||
have the same synopsis as the parameters for
|
||||
[`block-function-plugins`](#plugins.block.functions): They get the four
|
||||
parameters `$params`, `$content`, `$smarty` and `&$repeat` and they also
|
||||
behave like block-function-plugins.
|
||||
|
||||
|
||||
<?php
|
||||
// the object
|
||||
|
||||
class My_Object {
|
||||
function meth1($params, $smarty_obj) {
|
||||
return 'this is my meth1';
|
||||
}
|
||||
}
|
||||
|
||||
$myobj = new My_Object;
|
||||
|
||||
// registering the object (will be by reference)
|
||||
$smarty->registerObject('foobar',$myobj);
|
||||
|
||||
// if we want to restrict access to certain methods or properties, list them
|
||||
$smarty->registerObject('foobar',$myobj,array('meth1','meth2','prop1'));
|
||||
|
||||
// if you want to use the traditional object parameter format, pass a boolean of false
|
||||
$smarty->registerObject('foobar',$myobj,null,false);
|
||||
|
||||
// We can also assign objects. assign_by_ref when possible.
|
||||
$smarty->assign_by_ref('myobj', $myobj);
|
||||
|
||||
$smarty->display('index.tpl');
|
||||
?>
|
||||
|
||||
|
||||
|
||||
And here\'s how to access your objects in `index.tpl`:
|
||||
|
||||
|
||||
{* access our registered object *}
|
||||
{foobar->meth1 p1='foo' p2=$bar}
|
||||
|
||||
{* you can also assign the output *}
|
||||
{foobar->meth1 p1='foo' p2=$bar assign='output'}
|
||||
the output was {$output}
|
||||
|
||||
{* access our assigned object *}
|
||||
{$myobj->meth1('foo',$bar)}
|
||||
|
||||
|
||||
|
||||
See also [`registerObject()`](#api.register.object) and
|
||||
[`assign()`](#api.assign).
|
@ -1,43 +0,0 @@
|
||||
Output Filters {#advanced.features.outputfilters}
|
||||
==============
|
||||
|
||||
When the template is invoked via [`display()`](#api.display) or
|
||||
[`fetch()`](#api.fetch), its output can be sent through one or more
|
||||
output filters. This differs from
|
||||
[`postfilters`](#advanced.features.postfilters) because postfilters
|
||||
operate on compiled templates before they are saved to the disk, whereas
|
||||
output filters operate on the template output when it is executed.
|
||||
|
||||
Output filters can be either [registered](#api.register.filter) or
|
||||
loaded from the [plugins directory](#variable.plugins.dir) by using the
|
||||
[`loadFilter()`](#api.load.filter) method or by setting the
|
||||
[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will
|
||||
pass the template output as the first argument, and expect the function
|
||||
to return the result of the processing.
|
||||
|
||||
|
||||
<?php
|
||||
// put this in your application
|
||||
function protect_email($tpl_output, Smarty_Internal_Template $template)
|
||||
{
|
||||
$tpl_output =
|
||||
preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
|
||||
'$1%40$2', $tpl_output);
|
||||
return $tpl_output;
|
||||
}
|
||||
|
||||
// register the outputfilter
|
||||
$smarty->registerFilter("output","protect_email");
|
||||
$smarty->display("index.tpl');
|
||||
|
||||
// now any occurrence of an email address in the template output will have
|
||||
// a simple protection against spambots
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`registerFilter()`](#api.register.filter),
|
||||
[`loadFilter()`](#api.load.filter),
|
||||
[`$autoload_filters`](#variable.autoload.filters),
|
||||
[postfilters](#advanced.features.postfilters) and
|
||||
[`$plugins_dir`](#variable.plugins.dir).
|
@ -1,40 +0,0 @@
|
||||
Postfilters {#advanced.features.postfilters}
|
||||
===========
|
||||
|
||||
Template postfilters are PHP functions that your templates are ran
|
||||
through *after they are compiled*. Postfilters can be either
|
||||
[registered](#api.register.filter) or loaded from the [plugins
|
||||
directory](#variable.plugins.dir) by using the
|
||||
[`loadFilter()`](#api.load.filter) function or by setting the
|
||||
[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will
|
||||
pass the compiled template code as the first argument, and expect the
|
||||
function to return the result of the processing.
|
||||
|
||||
|
||||
<?php
|
||||
// put this in your application
|
||||
function add_header_comment($tpl_source, Smarty_Internal_Template $template)
|
||||
{
|
||||
return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source;
|
||||
}
|
||||
|
||||
// register the postfilter
|
||||
$smarty->registerFilter('post','add_header_comment');
|
||||
$smarty->display('index.tpl');
|
||||
?>
|
||||
|
||||
|
||||
|
||||
The postfilter above will make the compiled Smarty template `index.tpl`
|
||||
look like:
|
||||
|
||||
|
||||
<!-- Created by Smarty! -->
|
||||
{* rest of template content... *}
|
||||
|
||||
|
||||
|
||||
See also [`registerFilter()`](#api.register.filter),
|
||||
[prefilters](#advanced.features.prefilters),
|
||||
[outputfilters](#advanced.features.outputfilters), and
|
||||
[`loadFilter()`](#api.load.filter).
|
@ -1,36 +0,0 @@
|
||||
Prefilters {#advanced.features.prefilters}
|
||||
==========
|
||||
|
||||
Template prefilters are PHP functions that your templates are ran
|
||||
through *before they are compiled*. This is good for preprocessing your
|
||||
templates to remove unwanted comments, keeping an eye on what people are
|
||||
putting in their templates, etc.
|
||||
|
||||
Prefilters can be either [registered](#api.register.filter) or loaded
|
||||
from the [plugins directory](#variable.plugins.dir) by using
|
||||
[`loadFilter()`](#api.load.filter) function or by setting the
|
||||
[`$autoload_filters`](#variable.autoload.filters) variable.
|
||||
|
||||
Smarty will pass the template source code as the first argument, and
|
||||
expect the function to return the resulting template source code.
|
||||
|
||||
This will remove all the html comments in the template source.
|
||||
|
||||
|
||||
<?php
|
||||
// put this in your application
|
||||
function remove_dw_comments($tpl_source, Smarty_Internal_Template $template)
|
||||
{
|
||||
return preg_replace("/<!--#.*-->/U",'',$tpl_source);
|
||||
}
|
||||
|
||||
// register the prefilter
|
||||
$smarty->registerFilter('pre','remove_dw_comments');
|
||||
$smarty->display('index.tpl');
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`registerFilter()`](#api.register.filter),
|
||||
[postfilters](#advanced.features.postfilters) and
|
||||
[`loadFilter()`](#api.load.filter).
|
@ -1,144 +0,0 @@
|
||||
Security {#advanced.features.security}
|
||||
========
|
||||
|
||||
Security is good for situations when you have untrusted parties editing
|
||||
the templates e.g. via ftp, and you want to reduce the risk of system
|
||||
security compromises through the template language.
|
||||
|
||||
The settings of the security policy are defined by properties of an
|
||||
instance of the Smarty\_Security class. These are the possible settings:
|
||||
|
||||
- `$secure_dir` is an array of template directories that are
|
||||
considered secure. [`$template_dir`](#variable.template.dir)
|
||||
considered secure implicitly. The default is an empty array.
|
||||
|
||||
- `$trusted_dir` is an array of all directories that are considered
|
||||
trusted. Trusted directories are where you keep php scripts that are
|
||||
executed directly from the templates with
|
||||
[`{insert}`](#language.function.insert.php). The default is an
|
||||
empty array.
|
||||
|
||||
- `$trusted_uri` is an array of regular expressions matching URIs that
|
||||
are considered trusted. This security directive used by
|
||||
[`{fetch}`](#language.function.fetch) and
|
||||
[`{html_image}`](#language.function.html.image). URIs passed to
|
||||
these functions are reduced to `{$PROTOCOL}://{$HOSTNAME}` to allow
|
||||
simple regular expressions (without having to deal with edge cases
|
||||
like authentication-tokens).
|
||||
|
||||
The expression `'#https?://.*smarty.net$#i'` would allow accessing
|
||||
the following URIs:
|
||||
|
||||
- `http://smarty.net/foo`
|
||||
|
||||
- `http://smarty.net/foo`
|
||||
|
||||
- `http://www.smarty.net/foo`
|
||||
|
||||
- `http://smarty.net/foo`
|
||||
|
||||
- `https://foo.bar.www.smarty.net/foo/bla?blubb=1`
|
||||
|
||||
but deny access to these URIs:
|
||||
|
||||
- `http://smarty.com/foo` (not matching top-level domain \"com\")
|
||||
|
||||
- `ftp://www.smarty.net/foo` (not matching protocol \"ftp\")
|
||||
|
||||
- `http://www.smarty.net.otherdomain.com/foo` (not matching end of
|
||||
domain \"smarty.net\")
|
||||
|
||||
- `$static_classes` is an array of classes that are considered
|
||||
trusted. The default is an empty array which allows access to all
|
||||
static classes. To disable access to all static classes set
|
||||
\$static\_classes = null.
|
||||
|
||||
- `$php_functions` is an array of PHP functions that are considered
|
||||
trusted and can be used from within template. To disable access to
|
||||
all PHP functions set \$php\_functions = null. An empty array (
|
||||
\$php\_functions = array() ) will allow all PHP functions. The
|
||||
default is array(\'isset\', \'empty\', \'count\', \'sizeof\',
|
||||
\'in\_array\', \'is\_array\',\'time\',\'nl2br\').
|
||||
|
||||
- `$php_modifiers` is an array of PHP functions that are considered
|
||||
trusted and can be used from within template as modifier. To disable
|
||||
access to all PHP modifier set \$php\_modifier = null. An empty
|
||||
array ( \$php\_modifier = array() ) will allow all PHP functions.
|
||||
The default is array(\'escape\',\'count\').
|
||||
|
||||
- `$streams` is an array of streams that are considered trusted and
|
||||
can be used from within template. To disable access to all streams
|
||||
set \$streams = null. An empty array ( \$streams = array() ) will
|
||||
allow all streams. The default is array(\'file\').
|
||||
|
||||
- `$allowed_modifiers` is an array of (registered / autoloaded)
|
||||
modifiers that should be accessible to the template. If this array
|
||||
is non-empty, only the herein listed modifiers may be used. This is
|
||||
a whitelist.
|
||||
|
||||
- `$disabled_modifiers` is an array of (registered / autoloaded)
|
||||
modifiers that may not be accessible to the template.
|
||||
|
||||
- `$allowed_tags` is a boolean flag which controls if constants can
|
||||
function-, block and filter plugins that should be accessible to the
|
||||
template. If this array is non-empty, only the herein listed
|
||||
modifiers may be used. This is a whitelist.
|
||||
|
||||
- `$disabled_tags` is an array of (registered / autoloaded) function-,
|
||||
block and filter plugins that may not be accessible to the template.
|
||||
|
||||
- `$allow_constants` is a boolean flag which controls if constants can
|
||||
be accessed by the template. The default is \"true\".
|
||||
|
||||
- `$allow_super_globals` is a boolean flag which controls if the PHP
|
||||
super globals can be accessed by the template. The default is
|
||||
\"true\".
|
||||
|
||||
If security is enabled, no private methods, functions or properties of
|
||||
static classes or assigned objects can be accessed (beginning with
|
||||
\'\_\') by the template.
|
||||
|
||||
To customize the security policy settings you can extend the
|
||||
Smarty\_Security class or create an instance of it.
|
||||
|
||||
|
||||
<?php
|
||||
require 'Smarty.class.php';
|
||||
|
||||
class My_Security_Policy extends Smarty_Security {
|
||||
// disable all PHP functions
|
||||
public $php_functions = null;
|
||||
// allow everthing as modifier
|
||||
public $php_modifiers = array();
|
||||
}
|
||||
$smarty = new Smarty();
|
||||
// enable security
|
||||
$smarty->enableSecurity('My_Security_Policy');
|
||||
?>
|
||||
|
||||
|
||||
<?php
|
||||
require 'Smarty.class.php';
|
||||
$smarty = new Smarty();
|
||||
$my_security_policy = new Smarty_Security($smarty);
|
||||
// disable all PHP functions
|
||||
$my_security_policy->php_functions = null;
|
||||
// allow everthing as modifier
|
||||
$my_security_policy->php_modifiers = array();
|
||||
// enable security
|
||||
$smarty->enableSecurity($my_security_policy);
|
||||
?>
|
||||
|
||||
|
||||
<?php
|
||||
require 'Smarty.class.php';
|
||||
$smarty = new Smarty();
|
||||
// enable default security
|
||||
$smarty->enableSecurity();
|
||||
?>
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Most security policy settings are only checked when the template gets
|
||||
> compiled. For that reason you should delete all cached and compiled
|
||||
> template files when you change your security settings.
|
@ -1,27 +0,0 @@
|
||||
Static Classes {#advanced.features.static.classes}
|
||||
==============
|
||||
|
||||
You can directly access static classes. The syntax is the same as in
|
||||
PHP.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> Direct access to PHP classes is not recommended. This ties the
|
||||
> underlying application code structure directly to the presentation,
|
||||
> and also complicates template syntax. It is recommended to register
|
||||
> plugins which insulate templates from PHP classes/objects. Use at your
|
||||
> own discretion. See the Best Practices section of the Smarty website.
|
||||
|
||||
|
||||
{assign var=foo value=myclass::BAR} <--- class constant BAR
|
||||
|
||||
{assign var=foo value=myclass::method()} <--- method result
|
||||
|
||||
{assign var=foo value=myclass::method1()->method2} <--- method chaining
|
||||
|
||||
{assign var=foo value=myclass::$bar} <--- property bar of class myclass
|
||||
|
||||
{assign var=foo value=$bar::method} <--- using Smarty variable bar as class name
|
||||
|
||||
|
||||
|
@ -1,15 +0,0 @@
|
||||
Streams {#advanced.features.streams}
|
||||
=======
|
||||
|
||||
You can also use streams to call variables. *{\$foo:bar}* will use the
|
||||
*foo://bar* stream to get the template variable.
|
||||
|
||||
Using a PHP stream for a template variable resource from within a
|
||||
template.
|
||||
|
||||
|
||||
{$foo:bar}
|
||||
|
||||
|
||||
|
||||
See also [`Template Resources`](#resources)
|
@ -1,128 +0,0 @@
|
||||
Template Inheritance {#advanced.features.template.inheritance}
|
||||
====================
|
||||
|
||||
Inheritance brings the concept of Object Oriented Programming to
|
||||
templates, allowing you to define one (or more) base templates that can
|
||||
be extended by child templates. Extending means that the child template
|
||||
can override all or some of the parent named block areas.
|
||||
|
||||
- The inheritance tree can be as deep as you want, meaning you can
|
||||
extend a file that extends another one that extends another one and
|
||||
so on.
|
||||
|
||||
- The child templates can not define any content besides what\'s
|
||||
inside [`{block}`](#language.function.block) tags they override.
|
||||
Anything outside of [`{block}`](#language.function.block) tags will
|
||||
be removed.
|
||||
|
||||
- The content of [`{block}`](#language.function.block) tags from child
|
||||
and parent templates can be merged by the `append` or `prepend`
|
||||
[`{block}`](#language.function.block) tag option flags and
|
||||
`{$smarty.block.parent}` or `{$smarty.block.child}` placeholders.
|
||||
|
||||
- Template inheritance is a compile time process which creates a
|
||||
single compiled template file. Compared to corresponding solutions
|
||||
based on subtemplates included with the
|
||||
[`{include}`](#language.function.include) tag it does have much
|
||||
better performance when rendering.
|
||||
|
||||
- The child template extends its parent defined with the
|
||||
[`{extends}`](#language.function.extends) tag, which must be the
|
||||
first line in the child template. Instead of using the
|
||||
[`{extends}`](#language.function.extends) tags in the template files
|
||||
you can define the whole template inheritance tree in the PHP script
|
||||
when you are calling [`fetch()`](#api.fetch) or
|
||||
[`display()`](#api.display) with the `extends:` template resource
|
||||
type. The later provides even more flexibility.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> When `$compile_check` is enabled, all files in the inheritance tree
|
||||
> are checked for modifications upon each invocation. You may want to
|
||||
> disable `$compile_check` on production servers for this reason.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> If you have a subtemplate which is included with
|
||||
> [`{include}`](#language.function.include) and it contains
|
||||
> [`{block}`](#language.function.block) areas it works only if the
|
||||
> [`{include}`](#language.function.include) itself is called from within
|
||||
> a surrounding [`{block}`](#language.function.block). In the final
|
||||
> parent template you may need a dummy
|
||||
> [`{block}`](#language.function.block) for it.
|
||||
|
||||
layout.tpl (parent)
|
||||
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>{block name=title}Default Page Title{/block}</title>
|
||||
{block name=head}{/block}
|
||||
</head>
|
||||
<body>
|
||||
{block name=body}{/block}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
|
||||
myproject.tpl (child)
|
||||
|
||||
|
||||
{extends file='layout.tpl'}
|
||||
{block name=head}
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
{/block}
|
||||
|
||||
|
||||
|
||||
|
||||
mypage.tpl (grandchild)
|
||||
|
||||
|
||||
{extends file='myproject.tpl'}
|
||||
{block name=title}My Page Title{/block}
|
||||
{block name=head}
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
{/block}
|
||||
{block name=body}My HTML Page Body goes here{/block}
|
||||
|
||||
|
||||
|
||||
To render the above use
|
||||
|
||||
|
||||
$smarty->display('mypage.tpl');
|
||||
|
||||
The resulting output is
|
||||
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>My Page Title</title>
|
||||
<link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
|
||||
<script src="/js/mypage.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
My HTML Page Body goes here
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Instead of using [`{extends}`](#language.function.extends) tags in the
|
||||
template files you can define the inheritance tree in your PHP script by
|
||||
using the [`extends:` resource](#resources.extends) type.
|
||||
|
||||
The code below will return same result as the example above.
|
||||
|
||||
|
||||
<?php
|
||||
$smarty->display('extends:layout.tpl|myproject.tpl|mypage.tpl');
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`{block}`](#language.function.block),
|
||||
[`{extends}`](#language.function.extends) and [`extends:`
|
||||
resource](#resources.extends)
|
@ -1,32 +0,0 @@
|
||||
Changing settings by template {#advanced.features.template.settings}
|
||||
=============================
|
||||
|
||||
Normally you configure the Smarty settings by modifying the
|
||||
[`Smarty class variables`](#api.variables). Furthermore you can register
|
||||
plugins, filters etc. with [`Smarty functions`](#api.functions).
|
||||
Modifications done to the Smarty object will be global for all
|
||||
templates.
|
||||
|
||||
However the Smarty class variables and functions can be accessed or
|
||||
called by individual template objects. Modification done to a template
|
||||
object will apply only for that template and its included subtemplates.
|
||||
|
||||
|
||||
<?php
|
||||
$tpl = $smarty->createTemplate('index.tpl);
|
||||
$tpl->cache_lifetime = 600;
|
||||
//or
|
||||
$tpl->setCacheLifetime(600);
|
||||
$smarty->display($tpl);
|
||||
?>
|
||||
|
||||
|
||||
|
||||
|
||||
<?php
|
||||
$tpl = $smarty->createTemplate('index.tpl);
|
||||
$tpl->registerPlugin('modifier','mymodifier');
|
||||
$smarty->display($tpl);
|
||||
?>
|
||||
|
||||
|
@ -1,64 +0,0 @@
|
||||
Smarty Class Methods {#api.functions}
|
||||
====================
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [addConfigDir()](./api-functions/api-add-config-dir.md) — add a directory to the list of directories where config files are stored
|
||||
- [addPluginsDir()](./api-functions/api-add-plugins-dir.md) — add a directory to the list of directories where plugins are stored
|
||||
- [addTemplateDir()](./api-functions/api-add-template-dir.md) — add a directory to the list of directories where templates are stored
|
||||
- [append()](./api-functions/api-append.md) — append an element to an assigned array
|
||||
- [appendByRef()](./api-functions/api-append-by-ref.md) — append values by reference
|
||||
- [assign()](./api-functions/api-assign.md) — assign variables/objects to the templates
|
||||
- [assignByRef()](./api-functions/api-assign-by-ref.md) — assign values by reference
|
||||
- [clearAllAssign()](./api-functions/api-clear-all-assign.md) — clears the values of all assigned variables
|
||||
- [clearAllCache()](./api-functions/api-clear-all-cache.md) — clears the entire template cache
|
||||
- [clearAssign()](./api-functions/api-clear-assign.md) — clears the value of an assigned variable
|
||||
- [clearCache()](./api-functions/api-clear-cache.md) — clears the cache for a specific template
|
||||
- [clearCompiledTemplate()](./api-functions/api-clear-compiled-tpl.md) — clears the compiled version of the specified template resource
|
||||
- [clearConfig()](./api-functions/api-clear-config.md) — clears assigned config variables
|
||||
- [compileAllConfig()](./api-functions/api-compile-all-config.md) — compiles all known config files
|
||||
- [compileAllTemplates()](./api-functions/api-compile-all-templates.md) — compiles all known templates
|
||||
- [configLoad()](./api-functions/api-config-load.md) — loads config file data and assigns it to the template
|
||||
- [createData()](./api-functions/api-create-data.md) — creates a data object
|
||||
- [createTemplate()](./api-functions/api-create-template.md) — returns a template object
|
||||
- [disableSecurity()](./api-functions/api-disable-security.md) — disables template security
|
||||
- [display()](./api-functions/api-display.md) — displays the template
|
||||
- [enableSecurity()](./api-functions/api-enable-security.md) — enables template security
|
||||
- [fetch()](./api-functions/api-fetch.md) — returns the template output
|
||||
- [getCacheDir()](./api-functions/api-get-cache-dir.md) — return the directory where the rendered template's output is stored
|
||||
- [getCompileDir()](./api-functions/api-get-compile-dir.md) — returns the directory where compiled templates are stored
|
||||
- [getConfigDir()](./api-functions/api-get-config-dir.md) — return the directory where config files are stored
|
||||
- [getConfigVars()](./api-functions/api-get-config-vars.md) — returns the given loaded config variable value
|
||||
- [getPluginsDir()](./api-functions/api-get-plugins-dir.md) — return the directory where plugins are stored
|
||||
- [getRegisteredObject()](./api-functions/api-get-registered-object.md) — returns a reference to a registered object
|
||||
- [getTags()](./api-functions/api-get-tags.md) — return tags used by template
|
||||
- [getTemplateDir()](./api-functions/api-get-template-dir.md) — return the directory where templates are stored
|
||||
- [getTemplateVars()](./api-functions/api-get-template-vars.md) — returns assigned variable value(s)
|
||||
- [isCached()](./api-functions/api-is-cached.md) — returns true if there is a valid cache for this template
|
||||
- [loadFilter()](./api-functions/api-load-filter.md) — load a filter plugin
|
||||
- [muteExpectedErrors()](./api-functions/api-mute-expected-errors.md) — mutes expected warnings and notices deliberately generated by Smarty
|
||||
- [registerCacheResource()](./api-functions/api-register-cacheresource.md) — dynamically register CacheResources
|
||||
- [registerClass()](./api-functions/api-register-class.md) — register a class for use in the templates
|
||||
- [registerDefaultPluginHandler()](./api-functions/api-register-default-plugin-handler.md) — register a function which gets called on undefined tags
|
||||
- [registerFilter()](./api-functions/api-register-filter.md) — dynamically register filters
|
||||
- [registerPlugin()](./api-functions/api-register-plugin.md) — dynamically register plugins
|
||||
- [registerObject()](./api-functions/api-register-object.md) — register an object for use in the templates
|
||||
- [registerResource()](./api-functions/api-register-resource.md) — dynamically register resources
|
||||
- [setCacheDir()](./api-functions/api-set-cache-dir.md) — set the directory where the rendered template's output is stored
|
||||
- [setCompileDir()](./api-functions/api-set-compile-dir.md) — set the directory where compiled templates are stored
|
||||
- [setConfigDir()](./api-functions/api-set-config-dir.md) — set the directories where config files are stored
|
||||
- [setPluginsDir()](./api-functions/api-set-plugins-dir.md) — set the directories where plugins are stored
|
||||
- [setTemplateDir()](./api-functions/api-set-template-dir.md) — set the directories where templates are stored
|
||||
- [templateExists()](./api-functions/api-template-exists.md) — checks whether the specified template exists
|
||||
- [unregisterCacheResource()](./api-functions/api-unregister-cacheresource.md) — dynamically unregister a CacheResource plugin
|
||||
- [unregisterFilter()](./api-functions/api-unregister-filter.md) — dynamically unregister a filter
|
||||
- [unregisterPlugin()](./api-functions/api-unregister-plugin.md) — dynamically unregister plugins
|
||||
- [unregisterObject()](./api-functions/api-unregister-object.md) — dynamically unregister an object
|
||||
- [unregisterResource()](./api-functions/api-unregister-resource.md) — dynamically unregister a resource plugin
|
||||
- [testInstall()](./api-functions/api-test-install.md) — checks Smarty installation
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> See
|
||||
> [`Changing settings by template`](./advanced-features/advanced-features-template-settings.md)
|
||||
> section for how to use the functions for individual templates.
|
0
docs/programmers/api-functions/add-extension.md
Normal file
0
docs/programmers/api-functions/add-extension.md
Normal file
@ -1,49 +0,0 @@
|
||||
addConfigDir()
|
||||
|
||||
add a directory to the list of directories where config files are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
addConfigDir
|
||||
|
||||
string\|array
|
||||
|
||||
config\_dir
|
||||
|
||||
string
|
||||
|
||||
key
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// add directory where config files are stored
|
||||
$smarty->addConfigDir('./config_1');
|
||||
|
||||
// add directory where config files are stored and specify array-key
|
||||
$smarty->addConfigDir('./config_1', 'one');
|
||||
|
||||
// add multiple directories where config files are stored and specify array-keys
|
||||
$smarty->addTemplateDir(array(
|
||||
'two' => './config_2',
|
||||
'three' => './config_3',
|
||||
));
|
||||
|
||||
// view the template dir chain
|
||||
var_dump($smarty->getConfigDir());
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setConfigDir('./config')
|
||||
->addConfigDir('./config_1', 'one')
|
||||
->addConfigDir('./config_2', 'two');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getConfigDir()`](#api.get.config.dir),
|
||||
[`setConfigDir()`](#api.set.config.dir) and
|
||||
[`$config_dir`](#variable.config.dir).
|
@ -1,49 +0,0 @@
|
||||
addTemplateDir()
|
||||
|
||||
add a directory to the list of directories where templates are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
addTemplateDir
|
||||
|
||||
string\|array
|
||||
|
||||
template\_dir
|
||||
|
||||
string
|
||||
|
||||
key
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// add directory where templates are stored
|
||||
$smarty->addTemplateDir('./templates_1');
|
||||
|
||||
// add directory where templates are stored and specify array-key
|
||||
$smarty->addTemplateDir('./templates_1', 'one');
|
||||
|
||||
// add multiple directories where templates are stored and specify array-keys
|
||||
$smarty->addTemplateDir(array(
|
||||
'two' => './templates_2',
|
||||
'three' => './templates_3',
|
||||
));
|
||||
|
||||
// view the template dir chain
|
||||
var_dump($smarty->getTemplateDir());
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./templates')
|
||||
->addTemplateDir('./templates_1', 'one')
|
||||
->addTemplateDir('./templates_2', 'two');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getTemplateDir()`](#api.get.template.dir),
|
||||
[`setTemplateDir()`](#api.set.template.dir) and
|
||||
[`$template_dir`](#variable.template.dir).
|
@ -1,46 +0,0 @@
|
||||
appendByRef()
|
||||
|
||||
append values by reference
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
void
|
||||
|
||||
appendByRef
|
||||
|
||||
string
|
||||
|
||||
varname
|
||||
|
||||
mixed
|
||||
|
||||
var
|
||||
|
||||
bool
|
||||
|
||||
merge
|
||||
|
||||
This is used to [`append()`](#api.append) values to the templates by
|
||||
reference.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> With the introduction of PHP5, `appendByRef()` is not necessary for
|
||||
> most intents and purposes. `appendByRef()` is useful if you want a PHP
|
||||
> array index value to be affected by its reassignment from a template.
|
||||
> Assigned object properties behave this way by default.
|
||||
|
||||
NOTE.PARAMETER.MERGE
|
||||
|
||||
|
||||
<?php
|
||||
// appending name/value pairs
|
||||
$smarty->appendByRef('Name', $myname);
|
||||
$smarty->appendByRef('Address', $address);
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`append()`](#api.append), [`assign()`](#api.assign) and
|
||||
[`getTemplateVars()`](#api.get.template.vars).
|
@ -56,6 +56,5 @@ NOTE.PARAMETER.MERGE
|
||||
|
||||
|
||||
|
||||
See also [`appendByRef()`](#api.append.by.ref),
|
||||
[`assign()`](#api.assign) and
|
||||
See also [`assign()`](#api.assign) and
|
||||
[`getTemplateVars()`](#api.get.template.vars)
|
||||
|
@ -1,42 +0,0 @@
|
||||
assignByRef()
|
||||
|
||||
assign values by reference
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
void
|
||||
|
||||
assignByRef
|
||||
|
||||
string
|
||||
|
||||
varname
|
||||
|
||||
mixed
|
||||
|
||||
var
|
||||
|
||||
This is used to [`assign()`](#api.assign) values to the templates by
|
||||
reference.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> With the introduction of PHP5, `assignByRef()` is not necessary for
|
||||
> most intents and purposes. `assignByRef()` is useful if you want a PHP
|
||||
> array index value to be affected by its reassignment from a template.
|
||||
> Assigned object properties behave this way by default.
|
||||
|
||||
|
||||
<?php
|
||||
// passing name/value pairs
|
||||
$smarty->assignByRef('Name', $myname);
|
||||
$smarty->assignByRef('Address', $address);
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`assign()`](#api.assign),
|
||||
[`clearAllAssign()`](#api.clear.all.assign), [`append()`](#api.append),
|
||||
[`{assign}`](#language.function.assign) and
|
||||
[`getTemplateVars()`](#api.get.template.vars).
|
@ -78,7 +78,6 @@ To access more complex array assignments see
|
||||
[`{foreach}`](#language.function.foreach) and
|
||||
[`{section}`](#language.function.section)
|
||||
|
||||
See also [`assignByRef()`](#api.assign.by.ref),
|
||||
[`getTemplateVars()`](#api.get.template.vars),
|
||||
See also [`getTemplateVars()`](#api.get.template.vars),
|
||||
[`clearAssign()`](#api.clear.assign), [`append()`](#api.append) and
|
||||
[`{assign}`](#language.function.assign)
|
||||
|
@ -50,7 +50,7 @@ parameters:
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// force compilation of all config files
|
||||
|
@ -60,7 +60,7 @@ parameters:
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// force compilation of all template files
|
||||
|
@ -30,7 +30,7 @@ be used to control which variables are seen by which templates.
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// create data object with its private variable scope
|
||||
|
@ -80,7 +80,7 @@ following parameters:
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
// create template object with its private variable scope
|
||||
|
@ -31,7 +31,9 @@ PARAMETER.COMPILEID
|
||||
|
||||
|
||||
<?php
|
||||
include(SMARTY_DIR.'Smarty.class.php');
|
||||
|
||||
use Smarty\Smarty;
|
||||
|
||||
$smarty = new Smarty();
|
||||
$smarty->setCaching(true);
|
||||
|
||||
|
@ -30,7 +30,7 @@ PARAMETER.COMPILEID
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty;
|
||||
|
||||
$smarty->setCaching(true);
|
||||
|
@ -1,23 +0,0 @@
|
||||
getCacheDir()
|
||||
|
||||
return the directory where the rendered template\'s output is stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
string
|
||||
|
||||
getCacheDir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// get directory where compiled templates are stored
|
||||
$cacheDir = $smarty->getCacheDir();
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`setCacheDir()`](#api.set.cache.dir) and
|
||||
[`$cache_dir`](#variable.cache.dir).
|
@ -1,23 +0,0 @@
|
||||
getCompileDir()
|
||||
|
||||
returns the directory where compiled templates are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
string
|
||||
|
||||
getCompileDir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// get directory where compiled templates are stored
|
||||
$compileDir = $smarty->getCompileDir();
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`setCompileDir()`](#api.set.compile.dir) and
|
||||
[`$compile_dir`](#variable.compile.dir).
|
@ -1,40 +0,0 @@
|
||||
getTags()
|
||||
|
||||
return tags used by template
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
string
|
||||
|
||||
getTags
|
||||
|
||||
object
|
||||
|
||||
template
|
||||
|
||||
This function returns an array of tagname/attribute pairs for all tags
|
||||
used by the template. It uses the following parameters:
|
||||
|
||||
- `template` is the template object.
|
||||
|
||||
> **Note**
|
||||
>
|
||||
> This function is experimental.
|
||||
|
||||
|
||||
<?php
|
||||
include('Smarty.class.php');
|
||||
$smarty = new Smarty;
|
||||
|
||||
// create template object
|
||||
$tpl = $smarty->createTemplate('index.tpl');
|
||||
|
||||
// get tags
|
||||
$tags = $smarty->getTags($tpl);
|
||||
|
||||
print_r($tags);
|
||||
|
||||
?>
|
||||
|
||||
|
@ -1,40 +0,0 @@
|
||||
getTemplateDir()
|
||||
|
||||
return the directory where templates are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
string\|array
|
||||
|
||||
getTemplateDir
|
||||
|
||||
string
|
||||
|
||||
key
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// set some template directories
|
||||
$smarty->setTemplateDir(array(
|
||||
'one' => './templates',
|
||||
'two' => './templates_2',
|
||||
'three' => './templates_3',
|
||||
));
|
||||
|
||||
// get all directories where templates are stored
|
||||
$template_dir = $smarty->getTemplateDir();
|
||||
var_dump($template_dir); // array
|
||||
|
||||
// get directory identified by key
|
||||
$template_dir = $smarty->getTemplateDir('one');
|
||||
var_dump($template_dir); // string
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`setTemplateDir()`](#api.set.template.dir),
|
||||
[`addTemplateDir()`](#api.add.template.dir) and
|
||||
[`$template_dir`](#variable.template.dir).
|
@ -22,8 +22,8 @@ string
|
||||
compile\_id
|
||||
|
||||
- This only works if [`$caching`](#variable.caching) is set to one of
|
||||
`Smarty::CACHING_LIFETIME_CURRENT` or
|
||||
`Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching
|
||||
`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or
|
||||
`\Smarty\Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching
|
||||
section](#caching) for more info.
|
||||
|
||||
- You can also pass a `$cache_id` as an optional second parameter in
|
||||
|
@ -18,7 +18,7 @@ string
|
||||
name
|
||||
|
||||
The first argument specifies the type of the filter to load and can be
|
||||
one of the following: `pre`, `post` or `output`. The second argument
|
||||
one of the following: `variable`, `pre`, `post` or `output`. The second argument
|
||||
specifies the `name` of the filter plugin.
|
||||
|
||||
|
||||
@ -37,6 +37,5 @@ specifies the `name` of the filter plugin.
|
||||
|
||||
|
||||
|
||||
See also [`registerFilter()`](#api.register.filter),
|
||||
[`$autoload_filters`](#variable.autoload.filters) and [advanced
|
||||
See also [`registerFilter()`](#api.register.filter) and [advanced
|
||||
features](#advanced.features).
|
||||
|
@ -15,7 +15,7 @@ handler merely inspects `$errno` and `$errfile` to determine if the
|
||||
given error was produced deliberately and must be ignored, or should be
|
||||
passed on to the next error handler.
|
||||
|
||||
`Smarty::unmuteExpectedErrors()` removes the current error handler.
|
||||
`\Smarty\Smarty::unmuteExpectedErrors()` removes the current error handler.
|
||||
Please note, that if you\'ve registered any custom error handlers after
|
||||
the muteExpectedErrors() call, the unmute will not remove Smarty\'s
|
||||
muting error handler, but the one registered last.
|
||||
|
@ -31,7 +31,7 @@ how to create custom CacheResources.
|
||||
|
||||
|
||||
<?php
|
||||
$smarty->registerCacheResource('mysql', new Smarty_CacheResource_Mysql());
|
||||
$smarty->registerCacheResource('mysql', new My_CacheResource_Mysql());
|
||||
?>
|
||||
|
||||
|
||||
|
@ -24,6 +24,7 @@ otherwise. If security is enabled, classes registered with
|
||||
|
||||
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
|
||||
class Bar {
|
||||
$property = "hello world";
|
||||
@ -44,12 +45,14 @@ otherwise. If security is enabled, classes registered with
|
||||
|
||||
|
||||
<?php
|
||||
use Smarty\Smarty;
|
||||
|
||||
namespace my\php\application {
|
||||
class Bar {
|
||||
$property = "hello world";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$smarty = new Smarty();
|
||||
$smarty->registerClass("Foo", "\my\php\application\Bar");
|
||||
|
||||
|
@ -25,7 +25,7 @@ plugin types.
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
use Smarty\Smarty;
|
||||
$smarty = new Smarty();
|
||||
$smarty->registerDefaultPluginHandler('my_plugin_handler');
|
||||
|
||||
@ -37,7 +37,7 @@ plugin types.
|
||||
* @param string $name name of the undefined tag
|
||||
* @param string $type tag type (e.g. Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK,
|
||||
Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_MODIFIER, Smarty::PLUGIN_MODIFIERCOMPILER)
|
||||
* @param Smarty_Internal_Template $template template object
|
||||
* @param \Smarty\Template\ $template template object
|
||||
* @param string &$callback returned function name
|
||||
* @param string &$script optional returned script filepath if function is external
|
||||
* @param bool &$cacheable true by default, set to false if plugin is not cachable (Smarty >= 3.1.8)
|
||||
|
@ -38,8 +38,7 @@ filters](#advanced.features.outputfilters) for more information on how
|
||||
to set up an output filter function.
|
||||
|
||||
See also [`unregisterFilter()`](#api.unregister.filter),
|
||||
[`loadFilter()`](#api.load.filter),
|
||||
[`$autoload_filters`](#variable.autoload.filters), [template pre
|
||||
[`loadFilter()`](#api.load.filter), [template pre
|
||||
filters](#advanced.features.prefilters) [template post
|
||||
filters](#advanced.features.postfilters) [template output
|
||||
filters](#advanced.features.outputfilters) section.
|
||||
|
@ -32,9 +32,9 @@ cache\_attrs
|
||||
This method registers functions or methods defined in your script as
|
||||
plugin. It uses the following parameters:
|
||||
|
||||
- `cacheable` and `cache_attrs` can be omitted in most cases. See
|
||||
- `cacheable` can be omitted in most cases. See
|
||||
[controlling cacheability of plugins output](#caching.cacheable) on
|
||||
how to use them properly.
|
||||
how to use this properly.
|
||||
|
||||
<!-- -->
|
||||
|
||||
|
@ -37,7 +37,7 @@ information on how to setup a function for fetching templates.
|
||||
|
||||
|
||||
<?php
|
||||
$smarty->registerResource('mysql', new Smarty_Resource_Mysql());
|
||||
$smarty->registerResource('mysql', new My_Resource_Mysql());
|
||||
?>
|
||||
|
||||
|
||||
|
@ -1,32 +0,0 @@
|
||||
setCacheDir()
|
||||
|
||||
set the directory where the rendered template\'s output is stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
setCacheDir
|
||||
|
||||
string
|
||||
|
||||
cache\_dir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// set directory where rendered template's output is stored
|
||||
$smarty->setCacheDir('./cache');
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./templates')
|
||||
->setCompileDir('./templates_c')
|
||||
->setCacheDir('./cache');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getCacheDir()`](#api.get.cache.dir) and
|
||||
[`$cache_dir`](#variable.cache.dir).
|
@ -1,32 +0,0 @@
|
||||
setCompileDir()
|
||||
|
||||
set the directory where compiled templates are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
setCompileDir
|
||||
|
||||
string
|
||||
|
||||
compile\_dir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// set directory where compiled templates are stored
|
||||
$smarty->setCompileDir('./templates_c');
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./templates')
|
||||
->setCompileDir('./templates_c')
|
||||
->setCacheDir('./cache');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getCompileDir()`](#api.get.compile.dir) and
|
||||
[`$compile_dir`](#variable.compile.dir).
|
@ -1,47 +0,0 @@
|
||||
setConfigDir()
|
||||
|
||||
set the directories where config files are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
setConfigDir
|
||||
|
||||
string\|array
|
||||
|
||||
config\_dir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// set a single directory where the config files are stored
|
||||
$smarty->setConfigDir('./config');
|
||||
|
||||
// view the config dir chain
|
||||
var_dump($smarty->getConfigDir());
|
||||
|
||||
// set multiple directoríes where config files are stored
|
||||
$smarty->setConfigDir(array(
|
||||
'one' => './config',
|
||||
'two' => './config_2',
|
||||
'three' => './config_3',
|
||||
));
|
||||
|
||||
// view the config dir chain
|
||||
var_dump($smarty->getConfigDir());
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./templates')
|
||||
->setConfigDir('./config')
|
||||
->setCompileDir('./templates_c')
|
||||
->setCacheDir('./cache');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getConfigDir()`](#api.get.config.dir),
|
||||
[`addConfigDir()`](#api.add.config.dir) and
|
||||
[`$config_dir`](#variable.config.dir).
|
@ -1,46 +0,0 @@
|
||||
setTemplateDir()
|
||||
|
||||
set the directories where templates are stored
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Smarty
|
||||
|
||||
setTemplateDir
|
||||
|
||||
string\|array
|
||||
|
||||
template\_dir
|
||||
|
||||
|
||||
<?php
|
||||
|
||||
// set a single directory where the templates are stored
|
||||
$smarty->setTemplateDir('./cache');
|
||||
|
||||
// view the template dir chain
|
||||
var_dump($smarty->getTemplateDir());
|
||||
|
||||
// set multiple directoríes where templates are stored
|
||||
$smarty->setTemplateDir(array(
|
||||
'one' => './templates',
|
||||
'two' => './templates_2',
|
||||
'three' => './templates_3',
|
||||
));
|
||||
|
||||
// view the template dir chain
|
||||
var_dump($smarty->getTemplateDir());
|
||||
|
||||
// chaining of method calls
|
||||
$smarty->setTemplateDir('./templates')
|
||||
->setCompileDir('./templates_c')
|
||||
->setCacheDir('./cache');
|
||||
|
||||
?>
|
||||
|
||||
|
||||
|
||||
See also [`getTemplateDir()`](#api.get.template.dir),
|
||||
[`addTemplateDir()`](#api.add.template.dir) and
|
||||
[`$template_dir`](#variable.template.dir).
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user