* 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
11 KiB
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
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
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).
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
// 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:
{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
$smarty->display('file:/export/templates/index.tpl');
$smarty->display('file:/path/to/my/templates/menu.tpl');
And from within a Smarty template:
{include file='file:/usr/local/share/templates/navigation.tpl'}
Note
With
Security
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
$smarty->display('file:C:/export/templates/index.tpl');
$smarty->display('file:F:/path/to/my/templates/menu.tpl');
And from within Smarty template:
{include file='file:D:/usr/local/share/templates/navigation.tpl'}
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.
<?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), theeval:
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, thestring:
resource may be a better choice.
Note
With a
string:
resource type, each unique string generates a compiled file. Smarty cannot detect a string that has changed, and therefore will generate a new compiled file for each unique string. It is important to choose the correct resource so that you do not fill your disk space with wasted compiled strings.
<?php
$smarty->assign('foo', 'value');
$template_string = 'display {$foo} here';
$smarty->display('string:' . $template_string); // compiles for later reuse
$smarty->display('eval:' . $template_string); // compiles every time
From within a Smarty template:
{include file="string:$template_string"} {* compiles for later reuse *}
{include file="eval:$template_string"} {* compiles every time *}
Both string:
and eval:
resources may be encoded with
urlencode()
or
base64_encode()
. 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
.
<?php
$smarty->assign('foo','value');
$template_string_urlencode = urlencode('display {$foo} here');
$template_string_base64 = base64_encode('display {$foo} here');
$smarty->display('eval:urlencode:' . $template_string_urlencode); // will decode string using urldecode()
$smarty->display('eval:base64:' . $template_string_base64); // will decode string using base64_decode()
From within a Smarty template:
{include file="string:urlencode:$template_string_urlencode"} {* will decode string using urldecode() *}
{include file="eval:base64:$template_string_base64"} {* will decode string using base64_decode() *}
The extends resource
The extends:
resource is used to define child/parent relationships. For details see section of
Template inheritance.
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.
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
$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 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
stream_wrapper_register('myresource', MyResourceStream::class);
$smarty->display('myresource:bar.tpl');
Or, from within a template:
{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
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
$smarty->setDefaultResourceType('mysql');