pax_global_header 0000666 0000000 0000000 00000000064 13624573447 0014531 g ustar 00root root 0000000 0000000 52 comment=9c748d36b1838ee67fdbe117e9fe9c71cc211448
php-twig-2.12.5/ 0000775 0000000 0000000 00000000000 13624573447 0013357 5 ustar 00root root 0000000 0000000 php-twig-2.12.5/.editorconfig 0000664 0000000 0000000 00000000340 13624573447 0016031 0 ustar 00root root 0000000 0000000 ; top-most EditorConfig file
root = true
; Unix-style newlines
[*]
end_of_line = LF
[*.php]
indent_style = space
indent_size = 4
[*.test]
indent_style = space
indent_size = 4
[*.rst]
indent_style = space
indent_size = 4
php-twig-2.12.5/.gitignore 0000664 0000000 0000000 00000000072 13624573447 0015346 0 ustar 00root root 0000000 0000000 /composer.lock
/phpunit.xml
/vendor
.phpunit.result.cache
php-twig-2.12.5/.php_cs.dist 0000664 0000000 0000000 00000001437 13624573447 0015603 0 ustar 00root root 0000000 0000000 setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'@PHPUnit75Migration:risky' => true,
'php_unit_dedicate_assert' => ['target' => '5.6'],
'array_syntax' => ['syntax' => 'short'],
'php_unit_fqcn_annotation' => true,
'no_unreachable_default_argument_value' => false,
'braces' => ['allow_single_line_closure' => true],
'heredoc_to_nowdoc' => false,
'ordered_imports' => true,
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'all'],
])
->setRiskyAllowed(true)
->setFinder(PhpCsFixer\Finder::create()->in(__DIR__))
;
php-twig-2.12.5/.travis.yml 0000664 0000000 0000000 00000003363 13624573447 0015475 0 ustar 00root root 0000000 0000000 language: php
cache:
directories:
- vendor
- extra/*/vendor
- $HOME/.composer/cache/files
env:
global:
- SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1
- SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE=1
before_install:
- phpenv config-rm xdebug.ini || return 0
install:
- travis_retry composer install
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/cssinliner-extra && travis_retry composer install)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/html-extra && travis_retry composer install)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/inky-extra && travis_retry composer install)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/intl-extra && travis_retry composer install)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/markdown-extra && travis_retry composer install)
- ([[ $TRAVIS_PHP_VERSION < 7.2 ]] || cd extra/string-extra && travis_retry composer install)
script:
- ./vendor/bin/simple-phpunit
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/cssinliner-extra && ./vendor/bin/simple-phpunit)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/html-extra && ./vendor/bin/simple-phpunit)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/inky-extra && ./vendor/bin/simple-phpunit)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/intl-extra && ./vendor/bin/simple-phpunit)
- ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/markdown-extra && ./vendor/bin/simple-phpunit)
- ([[ $TRAVIS_PHP_VERSION < 7.2 ]] || cd extra/string-extra && ./vendor/bin/simple-phpunit)
jobs:
fast_finish: true
include:
- php: 7.0
- php: 7.1
- php: 7.2
- php: 7.3
- php: 7.4
- stage: integration tests
php: 7.3
script: ./drupal_test.sh
php-twig-2.12.5/CHANGELOG 0000664 0000000 0000000 00000171654 13624573447 0014607 0 ustar 00root root 0000000 0000000 * 2.12.5 (2020-02-11)
* Add a check to ensure that iconv() is defined
* 2.12.4 (2020-02-11)
* Avoid exceptions when an intl resource is not found
* Fix implementation of case-insensitivity for method names
* 2.12.3 (2019-12-28)
* fixed Symfony 5.0 support for the HTML extra extension
* fixed number formatter in Intl extra extension when using a formatter prototype
* 2.12.2 (2019-11-11)
* added supported for exponential numbers
* 2.12.1 (2019-10-17)
* added the String extension in the "extra" repositories: "u" filter
* 2.12.0 (2019-10-05)
* added the spaceship operator ("<=>"), useful when using an arrow function in the "sort" filter
* added support for an "arrow" function on the "sort" filter
* added the CssInliner extension in the "extra" repositories: "inline_css"
filter
* added the Inky extension in the "extra" repositories: "inky_to_html" filter
* added Intl extension in the "extra" repositories: "country_name",
"currency_name", "currency_symbol", "language_name", "locale_name",
"timezone_name", "format_currency", "format_number",
"format_*_number", "format_datetime", "format_date", and "format_time"
filters, and the "country_timezones" function
* added the Markdown extension in the "extra" repositories: "markdown_to_html",
and "html_to_markdown" filters
* added the HtmlExtension extension in the "extra" repositories: "date_uri"
filter, and "html_classes" function
* optimized "block('foo') ?? 'bar'"
* fixed the empty test on Traversable instances
* fixed array_key_exists() on objects
* fixed cache when opcache is installed but disabled
* fixed using macros in arrow functions
* fixed split filter on edge case
* 2.11.3 (2019-06-18)
* display partial output (PHP buffer) when an error occurs in debug mode
* fixed the filter filter (allow the result to be used several times)
* fixed macro auto-import when a template contains only macros
* 2.11.2 (2019-06-05)
* fixed macro auto-import
* 2.11.1 (2019-06-04)
* added support for "Twig\Markup" instances in the "in" test (again)
* allowed string operators as variables names in assignments
* fixed support for macros defined in parent templates
* 2.11.0 (2019-05-31)
* added the possibility to register classes/interfaces as being safe for the escaper ("EscaperExtension::addSafeClass()")
* deprecated CoreExtension::setEscaper() and CoreExtension::getEscapers() in favor of the same methods on EscaperExtension
* macros are now auto-imported in the template they are defined (under the ``_self`` variable)
* added support for macros on "is defined" tests
* fixed macros "import" when using the same name in the parent and child templates
* fixed recursive macros
* macros imported "globally" in a template are now available in macros without re-importing them
* fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance)
* fixed a PHP fatal error when calling a macro imported in a block in a nested block
* fixed a PHP fatal error when calling a macro imported in the template in another macro
* fixed wrong error message on "import" and "from"
* 2.10.0 (2019-05-14)
* deprecated "if" conditions on "for" tags
* added "filter", "map", and "reduce" filters (and support for arrow functions)
* fixed partial output leak when a PHP fatal error occurs
* optimized context access on PHP 7.4
* 2.9.0 (2019-04-28)
* deprecated returning "false" to remove a Node from NodeVisitorInterface::leaveNode()
* allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning)
* deprecated the "filter" tag (use the "apply" tag instead)
* added the "apply" tag as a replacement for the "filter" tag
* allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning)
* added support for "Twig\Markup" instances in the "in" test
* fixed "import" when macros are stored in a template string
* fixed Lexer when using custom options containing the # char
* added template line number to twig_get_attribute()
* 2.8.1 (2019-04-16)
* fixed EscaperNodeVisitor
* deprecated passing a 3rd, 4th, and 5th arguments to the Sandbox exception classes
* deprecated Node::setTemplateName() in favor of Node::setSourceContext()
* 2.8.0 (2019-04-16)
* added Traversable support for the length filter
* fixed some wrong location in error messages
* made exception creation faster
* made escaping on ternary expressions (?: and ??) more fine-grained
* added the possibility to give a nice name to string templates (template_from_string function)
* fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags)
* fixed "include" with "ignore missing" when an error loading occurs in the included template
* added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#})
* added the "column" filter
* 2.7.4 (2019-03-23)
* fixed variadic support
* fixed CheckToStringNode implementation (broken when a function/filter is variadic)
* 2.7.3 (2019-03-21)
* fixed the spaceless filter so that it behaves like the spaceless tag
* fixed BC break on Environment::resolveTemplate()
* allowed Traversable objects to be used in the "with" tag
* allowed Traversable objects to be used in the "with" tag
* allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags
* 2.7.2 (2019-03-12)
* added TemplateWrapper::getTemplateName()
* 2.7.1 (2019-03-12)
* fixed class aliases
* 2.7.0 (2019-03-12)
* fixed sandbox security issue (under some circumstances, calling the
__toString() method on an object was possible even if not allowed by the
security policy)
* fixed batch filter clobbers array keys when fill parameter is used
* added preserveKeys support for the batch filter
* fixed "embed" support when used from "template_from_string"
* deprecated passing a Twig\Template to Twig\Environment::load()/Twig\Environment::resolveTemplate()
* added the possibility to pass a TemplateWrapper to Twig\Environment::load()
* marked Twig\Environment::getTemplateClass() as internal (implementation detail)
* improved the performance of the sandbox
* deprecated the spaceless tag
* added a spaceless filter
* added max value to the "random" function
* deprecated Twig\Extension\InitRuntimeInterface
* deprecated Twig\Loader\ExistsLoaderInterface
* deprecated PSR-0 classes in favor of namespaced ones
* made namespace classes the default classes (PSR-0 ones are aliases now)
* added Twig\Loader\ChainLoader::getLoaders()
* removed duplicated directory separator in FilesystemLoader
* deprecated the "base_template_class" option on Twig\Environment
* deprecated the Twig\Environment::getBaseTemplateClass() and
Twig\Environment::setBaseTemplateClass() methods
* changed internal code to use the namespaced classes as much as possible
* deprecated Twig_Parser::isReservedMacroName()
* 2.6.2 (2019-01-14)
* fixed regression (key exists check for non ArrayObject objects)
* 2.6.1 (2019-01-14)
* fixed ArrayObject access with a null value
* fixed embedded templates starting with a BOM
* fixed using a Twig_TemplateWrapper instance as an argument to extends
* fixed error location when calling an undefined block
* deprecated passing a string as a source on Twig_Error
* switched generated code to use the PHP short array notation
* fixed float representation in compiled templates
* added a second argument to the join filter (last separator configuration)
* 2.6.0 (2018-12-16)
* made sure twig_include returns a string
* fixed multi-byte UFT-8 in escape('html_attr')
* added the "deprecated" tag
* added support for dynamically named tests
* fixed GlobalsInterface extended class
* fixed filesystem loader throwing an exception instead of returning false
* 2.5.0 (2018-07-13)
* deprecated using the spaceless tag at the root level of a child template (noop anyway)
* deprecated the possibility to define a block in a non-capturing block in a child template
* added the Symfony ctype polyfill as a dependency
* fixed reporting the proper location for errors compiled in templates
* fixed the error handling for the optimized extension-based function calls
* ensured that syntax errors are triggered with the right line
* "js" filter now produces valid JSON
* 2.4.8 (2018-04-02)
* fixed a regression when using the "default" filter or the "defined" test on non-existing arrays
* 2.4.7 (2018-03-20)
* optimized runtime performance
* optimized parser performance by inlining the constant values
* fixed block names unicity
* fixed counting children of SimpleXMLElement objects
* added missing else clause to avoid infinite loops
* fixed .. (range operator) in sandbox policy
* 2.4.6 (2018-03-03)
* fixed a regression in the way the profiler is registered in templates
* 2.4.5 (2018-03-02)
* optimized the performance of calling an extension method at runtime
* optimized the performance of the dot operator for array and method calls
* added an exception when using "===" instead of "same as"
* fixed possible array to string conversion concealing actual error
* made variable names deterministic in compiled templates
* fixed length filter when passing an instance of IteratorAggregate
* fixed Environment::resolveTemplate to accept instances of TemplateWrapper
* 2.4.4 (2017-09-27)
* added Twig_Profiler_Profile::reset()
* fixed use TokenParser to return an empty Node
* added RuntimeExtensionInterface
* added circular reference detection when loading templates
* added support for runtime loaders in IntegrationTestCase
* fixed deprecation when using Twig_Profiler_Dumper_Html
* removed @final from Twig_Profiler_Dumper_Text
* 2.4.3 (2017-06-07)
* fixed namespaces introduction
* 2.4.2 (2017-06-05)
* fixed namespaces introduction
* 2.4.1 (2017-06-05)
* fixed namespaces introduction
* 2.4.0 (2017-06-05)
* added support for PHPUnit 6 when testing extensions
* fixed PHP 7.2 compatibility
* fixed template name generation in Twig_Environment::createTemplate()
* removed final tag on Twig_TokenParser_Include
* dropped HHVM support
* added namespaced aliases for all (non-deprecated) classes and interfaces
* marked Twig_Filter, Twig_Function, Twig_Test, Twig_Node_Module and Twig_Profiler_Profile as final via the @final annotation
* 2.3.2 (2017-04-20)
* fixed edge case in the method cache for Twig attributes
* 2.3.1 (2017-04-18)
* fixed the empty() test
* 2.3.0 (2017-03-22)
* fixed a race condition handling when writing cache files
* "length" filter now returns string length when applied to an object that does
not implement \Countable but provides __toString()
* "empty" test will now consider the return value of the __toString() method for
objects implement __toString() but not \Countable
* fixed JS escaping for unicode characters with higher code points
* added error message when calling `parent()` in a block that doesn't exist in the parent template
* 2.2.0 (2017-02-26)
* added a PSR-11 compatible runtime loader
* added `side` argument to `trim` to allow left or right trimming only.
* 2.1.0 (2017-01-11)
* fixed twig_get_attribute()
* added Twig_NodeCaptureInterface for nodes that capture all output
* 2.0.0 (2017-01-05)
* removed the C extension
* moved Twig_Environment::getAttribute() to twig_get_attribute()
* removed Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler()
* removed Twig_Compiler::getFilename()
* added hasser support in Twig_Template::getAttribute()
* sped up the json_encode filter
* removed reserved macro names; all names can be used as macro
* removed Twig_Template::getEnvironment()
* changed _self variable to return the current template name
* made the loader a required argument of Twig_Environment constructor
* removed Twig_Environment::clearTemplateCache()
* removed Twig_Autoloader (use Composer instead)
* removed `true` as an equivalent to `html` for the auto-escaping strategy
* removed pre-1.8 autoescape tag syntax
* dropped support for PHP 5.x
* removed the ability to register a global variable after the runtime or the extensions have been initialized
* improved the performance of the filesystem loader
* removed features that were deprecated in 1.x
* 1.42.6 (2020-XX-XX)
* n/a
* 1.42.5 (2020-02-11)
* Fix implementation of case-insensitivity for method names
* 1.42.4 (2019-11-11)
* optimized "block('foo') ?? 'bar"
* added supported for exponential numbers
* 1.42.3 (2019-08-24)
* fixed the "split" filter when the delimiter is "0"
* fixed the "empty" test on Traversable instances
* fixed cache when opcache is installed but disabled
* fixed PHP 7.4 compatibility
* bumped the minimal PHP version to 5.5
* 1.42.2 (2019-06-18)
* Display partial output (PHP buffer) when an error occurs in debug mode
* 1.42.1 (2019-06-04)
* added support for "Twig\Markup" instances in the "in" test (again)
* allowed string operators as variables names in assignments
* 1.42.0 (2019-05-31)
* fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance)
* fixed a PHP fatal error when calling a macro imported in a block in a nested block
* fixed a PHP fatal error when calling a macro imported in the template in another macro
* fixed wrong error message on "import" and "from"
* 1.41.0 (2019-05-14)
* fixed support for PHP 7.4
* added "filter", "map", and "reduce" filters (and support for arrow functions)
* fixed partial output leak when a PHP fatal error occurs
* optimized context access on PHP 7.4
* 1.40.1 (2019-04-29)
* fixed regression in NodeTraverser
* 1.40.0 (2019-04-28)
* allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning)
* added the "apply" tag as a replacement for the "filter" tag
* allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning)
* added support for "Twig\Markup" instances in the "in" test
* fixed Lexer when using custom options containing the # char
* fixed "import" when macros are stored in a template string
* 1.39.1 (2019-04-16)
* fixed EscaperNodeVisitor
* 1.39.0 (2019-04-16)
* added Traversable support for the length filter
* fixed some wrong location in error messages
* made exception creation faster
* made escaping on ternary expressions (?: and ??) more fine-grained
* added the possibility to give a nice name to string templates (template_from_string function)
* fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags)
* fixed "include" with "ignore missing" when an error loading occurs in the included template
* added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#})
* 1.38.4 (2019-03-23)
* fixed CheckToStringNode implementation (broken when a function/filter is variadic)
* 1.38.3 (2019-03-21)
* fixed the spaceless filter so that it behaves like the spaceless tag
* fixed BC break on Environment::resolveTemplate()
* fixed the bundled Autoloader to also load namespaced classes
* allowed Traversable objects to be used in the "with" tag
* allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags
* 1.38.2 (2019-03-12)
* added TemplateWrapper::getTemplateName()
* 1.38.1 (2019-03-12)
* fixed class aliases
* 1.38.0 (2019-03-12)
* fixed sandbox security issue (under some circumstances, calling the
__toString() method on an object was possible even if not allowed by the
security policy)
* fixed batch filter clobbers array keys when fill parameter is used
* added preserveKeys support for the batch filter
* fixed "embed" support when used from "template_from_string"
* added the possibility to pass a TemplateWrapper to Twig\Environment::load()
* improved the performance of the sandbox
* added a spaceless filter
* added max value to the "random" function
* made namespace classes the default classes (PSR-0 ones are aliases now)
* removed duplicated directory separator in FilesystemLoader
* added Twig\Loader\ChainLoader::getLoaders()
* changed internal code to use the namespaced classes as much as possible
* 1.37.1 (2019-01-14)
* fixed regression (key exists check for non ArrayObject objects)
* fixed logic in TemplateWrapper
* 1.37.0 (2019-01-14)
* fixed ArrayObject access with a null value
* fixed embedded templates starting with a BOM
* fixed using a Twig_TemplateWrapper instance as an argument to extends
* switched generated code to use the PHP short array notation
* dropped PHP 5.3 support
* fixed float representation in compiled templates
* added a second argument to the join filter (last separator configuration)
* 1.36.0 (2018-12-16)
* made sure twig_include returns a string
* fixed multi-byte UFT-8 in escape('html_attr')
* added the "deprecated" tag
* added support for dynamically named tests
* fixed GlobalsInterface extended class
* fixed filesystem loader throwing an exception instead of returning false
* 1.35.4 (2018-07-13)
* ensured that syntax errors are triggered with the right line
* added the Symfony ctype polyfill as a dependency
* "js" filter now produces valid JSON
* 1.35.3 (2018-03-20)
* fixed block names unicity
* fixed counting children of SimpleXMLElement objects
* added missing else clause to avoid infinite loops
* fixed .. (range operator) in sandbox policy
* 1.35.2 (2018-03-03)
* fixed a regression in the way the profiler is registered in templates
* 1.35.1 (2018-03-02)
* added an exception when using "===" instead of "same as"
* fixed possible array to string conversion concealing actual error
* made variable names deterministic in compiled templates
* fixed length filter when passing an instance of IteratorAggregate
* fixed Environment::resolveTemplate to accept instances of TemplateWrapper
* 1.35.0 (2017-09-27)
* added Twig_Profiler_Profile::reset()
* fixed use TokenParser to return an empty Node
* added RuntimeExtensionInterface
* added circular reference detection when loading templates
* 1.34.4 (2017-07-04)
* added support for runtime loaders in IntegrationTestCase
* fixed deprecation when using Twig_Profiler_Dumper_Html
* 1.34.3 (2017-06-07)
* fixed namespaces introduction
* 1.34.2 (2017-06-05)
* fixed namespaces introduction
* 1.34.1 (2017-06-05)
* fixed namespaces introduction
* 1.34.0 (2017-06-05)
* added support for PHPUnit 6 when testing extensions
* fixed PHP 7.2 compatibility
* fixed template name generation in Twig_Environment::createTemplate()
* removed final tag on Twig_TokenParser_Include
* added namespaced aliases for all (non-deprecated) classes and interfaces
* dropped HHVM support
* dropped PHP 5.2 support
* 1.33.2 (2017-04-20)
* fixed edge case in the method cache for Twig attributes
* 1.33.1 (2017-04-18)
* fixed the empty() test
* 1.33.0 (2017-03-22)
* fixed a race condition handling when writing cache files
* "length" filter now returns string length when applied to an object that does
not implement \Countable but provides __toString()
* "empty" test will now consider the return value of the __toString() method for
objects implement __toString() but not \Countable
* fixed JS escaping for unicode characters with higher code points
* 1.32.0 (2017-02-26)
* fixed deprecation notice in Twig_Util_DeprecationCollector
* added a PSR-11 compatible runtime loader
* added `side` argument to `trim` to allow left or right trimming only.
* 1.31.0 (2017-01-11)
* added Twig_NodeCaptureInterface for nodes that capture all output
* fixed marking the environment as initialized too early
* fixed C89 compat for the C extension
* turned fatal error into exception when a previously generated cache is corrupted
* fixed offline cache warm-ups for embedded templates
* 1.30.0 (2016-12-23)
* added Twig_FactoryRuntimeLoader
* deprecated function/test/filter/tag overriding
* deprecated the "disable_c_ext" attribute on Twig_Node_Expression_GetAttr
* 1.29.0 (2016-12-13)
* fixed sandbox being left enabled if an exception is thrown while rendering
* marked some classes as being final (via @final)
* made Twig_Error report real source path when possible
* added support for {{ _self }} to provide an upgrade path from 1.x to 2.0 (replaces {{ _self.templateName }})
* deprecated silent display of undefined blocks
* deprecated support for mbstring.func_overload != 0
* 1.28.2 (2016-11-23)
* fixed precedence between getFoo() and isFoo() in Twig_Template::getAttribute()
* improved a deprecation message
* 1.28.1 (2016-11-18)
* fixed block() function when used with a template argument
* 1.28.0 (2016-11-17)
* added support for the PHP 7 null coalescing operator for the ?? Twig implementation
* exposed a way to access template data and methods in a portable way
* changed context access to use the PHP 7 null coalescing operator when available
* added the "with" tag
* added support for a custom template on the block() function
* added "is defined" support for block() and constant()
* optimized the way attributes are fetched
* 1.27.0 (2016-10-25)
* deprecated Twig_Parser::getEnvironment()
* deprecated Twig_Parser::addHandler() and Twig_Parser::addNodeVisitor()
* deprecated Twig_Compiler::addIndentation()
* fixed regression when registering two extensions having the same class name
* deprecated Twig_LoaderInterface::getSource() (implement Twig_SourceContextLoaderInterface instead)
* fixed the filesystem loader with relative paths
* deprecated Twig_Node::getLine() in favor of Twig_Node::getTemplateLine()
* deprecated Twig_Template::getSource() in favor of Twig_Template::getSourceContext()
* deprecated Twig_Node::getFilename() in favor of Twig_Node::getTemplateName()
* deprecated the "filename" escaping strategy (use "name" instead)
* added Twig_Source to hold information about the original template
* deprecated Twig_Error::getTemplateFile() and Twig_Error::setTemplateFile() in favor of Twig_Error::getTemplateName() and Twig_Error::setTemplateName()
* deprecated Parser::getFilename()
* fixed template paths when a template name contains a protocol like vfs://
* improved debugging with Twig_Sandbox_SecurityError exceptions for disallowed methods and properties
* 1.26.1 (2016-10-05)
* removed template source code from generated template classes when debug is disabled
* fixed default implementation of Twig_Template::getDebugInfo() for better BC
* fixed regression on static calls for functions/filters/tests
* 1.26.0 (2016-10-02)
* added template cache invalidation based on more environment options
* added a missing deprecation notice
* fixed template paths when a template is stored in a PHAR file
* allowed filters/functions/tests implementation to use a different class than the extension they belong to
* deprecated Twig_ExtensionInterface::getName()
* 1.25.0 (2016-09-21)
* changed the way we store template source in template classes
* removed usage of realpath in cache keys
* fixed Twig cache sharing when used with different versions of PHP
* removed embed parent workaround for simple use cases
* deprecated the ability to store non Node instances in Node::$nodes
* deprecated Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler()
* deprecated Twig_Compiler::getFilename()
* 1.24.2 (2016-09-01)
* fixed static callables
* fixed a potential PHP warning when loading the cache
* fixed a case where the autoescaping does not work as expected
* 1.24.1 (2016-05-30)
* fixed reserved keywords (forbids true, false, null and none keywords for variables names)
* fixed support for PHP7 (Throwable support)
* marked the following methods as being internals on Twig_Environment:
getFunctions(), getFilters(), getTests(), getFunction(), getFilter(), getTest(),
getTokenParsers(), getTags(), getNodeVisitors(), getUnaryOperators(), getBinaryOperators(),
getFunctions(), getFilters(), getGlobals(), initGlobals(), initExtensions(), and initExtension()
* 1.24.0 (2016-01-25)
* adding support for the ?? operator
* fixed the defined test when used on a constant, a map, or a sequence
* undeprecated _self (should only be used to get the template name, not the template instance)
* fixed parsing on PHP7
* 1.23.3 (2016-01-11)
* fixed typo
* 1.23.2 (2015-01-11)
* added versions in deprecated messages
* made file cache tolerant for trailing (back)slashes on directory configuration
* deprecated unused Twig_Node_Expression_ExtensionReference class
* 1.23.1 (2015-11-05)
* fixed some exception messages which triggered PHP warnings
* fixed BC on Twig_Test_NodeTestCase
* 1.23.0 (2015-10-29)
* deprecated the possibility to override an extension by registering another one with the same name
* deprecated Twig_ExtensionInterface::getGlobals() (added Twig_Extension_GlobalsInterface for BC)
* deprecated Twig_ExtensionInterface::initRuntime() (added Twig_Extension_InitRuntimeInterface for BC)
* deprecated Twig_Environment::computeAlternatives()
* 1.22.3 (2015-10-13)
* fixed regression when using null as a cache strategy
* improved performance when checking template freshness
* fixed warnings when loaded templates do not exist
* fixed template class name generation to prevent possible collisions
* fixed logic for custom escapers to call them even on integers and null values
* changed template cache names to take into account the Twig C extension
* 1.22.2 (2015-09-22)
* fixed a race condition in template loading
* 1.22.1 (2015-09-15)
* fixed regression in template_from_string
* 1.22.0 (2015-09-13)
* made Twig_Test_IntegrationTestCase more flexible
* added an option to force PHP bytecode invalidation when writing a compiled template into the cache
* fixed the profiler duration for the root node
* changed template cache names to take into account enabled extensions
* deprecated Twig_Environment::clearCacheFiles(), Twig_Environment::getCacheFilename(),
Twig_Environment::writeCacheFile(), and Twig_Environment::getTemplateClassPrefix()
* added a way to override the filesystem template cache system
* added a way to get the original template source from Twig_Template
* 1.21.2 (2015-09-09)
* fixed variable names for the deprecation triggering code
* fixed escaping strategy detection based on filename
* added Traversable support for replace, merge, and sort
* deprecated support for character by character replacement for the "replace" filter
* 1.21.1 (2015-08-26)
* fixed regression when using the deprecated Twig_Test_* classes
* 1.21.0 (2015-08-24)
* added deprecation notices for deprecated features
* added a deprecation "framework" for filters/functions/tests and test fixtures
* 1.20.0 (2015-08-12)
* forbid access to the Twig environment from templates and internal parts of Twig_Template
* fixed limited RCEs when in sandbox mode
* deprecated Twig_Template::getEnvironment()
* deprecated the _self variable for usage outside of the from and import tags
* added Twig_BaseNodeVisitor to ease the compatibility of node visitors
between 1.x and 2.x
* 1.19.0 (2015-07-31)
* fixed wrong error message when including an undefined template in a child template
* added support for variadic filters, functions, and tests
* added support for extra positional arguments in macros
* added ignore_missing flag to the source function
* fixed batch filter with zero items
* deprecated Twig_Environment::clearTemplateCache()
* fixed sandbox disabling when using the include function
* 1.18.2 (2015-06-06)
* fixed template/line guessing in exceptions for nested templates
* optimized the number of inodes and the size of realpath cache when using the cache
* 1.18.1 (2015-04-19)
* fixed memory leaks in the C extension
* deprecated Twig_Loader_String
* fixed the slice filter when used with a SimpleXMLElement object
* fixed filesystem loader when trying to load non-files (like directories)
* 1.18.0 (2015-01-25)
* fixed some error messages where the line was wrong (unknown variables or argument names)
* added a new way to customize the main Module node (via empty nodes)
* added Twig_Environment::createTemplate() to create a template from a string
* added a profiler
* fixed filesystem loader cache when different file paths are used for the same template
* 1.17.0 (2015-01-14)
* added a 'filename' autoescaping strategy, which dynamically chooses the
autoescaping strategy for a template based on template file extension.
* 1.16.3 (2014-12-25)
* fixed regression for dynamic parent templates
* fixed cache management with statcache
* fixed a regression in the slice filter
* 1.16.2 (2014-10-17)
* fixed timezone on dates as strings
* fixed 2-words test names when a custom node class is not used
* fixed macros when using an argument named like a PHP super global (like GET or POST)
* fixed date_modify when working with DateTimeImmutable
* optimized for loops
* fixed multi-byte characters handling in the split filter
* fixed a regression in the in operator
* fixed a regression in the slice filter
* 1.16.1 (2014-10-10)
* improved error reporting in a sandboxed template
* fixed missing error file/line information under certain circumstances
* fixed wrong error line number in some error messages
* fixed the in operator to use strict comparisons
* sped up the slice filter
* fixed for mb function overload mb_substr acting different
* fixed the attribute() function when passing a variable for the arguments
* 1.16.0 (2014-07-05)
* changed url_encode to always encode according to RFC 3986
* fixed inheritance in a 'use'-hierarchy
* removed the __toString policy check when the sandbox is disabled
* fixed recursively calling blocks in templates with inheritance
* 1.15.1 (2014-02-13)
* fixed the conversion of the special '0000-00-00 00:00' date
* added an error message when trying to import an undefined block from a trait
* fixed a C extension crash when accessing defined but uninitialized property.
* 1.15.0 (2013-12-06)
* made ignoreStrictCheck in Template::getAttribute() works with __call() methods throwing BadMethodCallException
* added min and max functions
* added the round filter
* fixed a bug that prevented the optimizers to be enabled/disabled selectively
* fixed first and last filters for UTF-8 strings
* added a source function to include the content of a template without rendering it
* fixed the C extension sandbox behavior when get or set is prepend to method name
* 1.14.2 (2013-10-30)
* fixed error filename/line when an error occurs in an included file
* allowed operators that contain whitespaces to have more than one whitespace
* allowed tests to be made of 1 or 2 words (like "same as" or "divisible by")
* 1.14.1 (2013-10-15)
* made it possible to use named operators as variables
* fixed the possibility to have a variable named 'matches'
* added support for PHP 5.5 DateTimeInterface
* 1.14.0 (2013-10-03)
* fixed usage of the html_attr escaping strategy to avoid double-escaping with the html strategy
* added new operators: ends with, starts with, and matches
* fixed some compatibility issues with HHVM
* added a way to add custom escaping strategies
* fixed the C extension compilation on Windows
* fixed the batch filter when using a fill argument with an exact match of elements to batch
* fixed the filesystem loader cache when a template name exists in several namespaces
* fixed template_from_string when the template includes or extends other ones
* fixed a crash of the C extension on an edge case
* 1.13.2 (2013-08-03)
* fixed the error line number for an error occurs in and embedded template
* fixed crashes of the C extension on some edge cases
* 1.13.1 (2013-06-06)
* added the possibility to ignore the filesystem constructor argument in Twig_Loader_Filesystem
* fixed Twig_Loader_Chain::exists() for a loader which implements Twig_ExistsLoaderInterface
* adjusted backtrace call to reduce memory usage when an error occurs
* added support for object instances as the second argument of the constant test
* fixed the include function when used in an assignment
* 1.13.0 (2013-05-10)
* fixed getting a numeric-like item on a variable ('09' for instance)
* fixed getting a boolean or float key on an array, so it is consistent with PHP's array access:
`{{ array[false] }}` behaves the same as `echo $array[false];` (equals `$array[0]`)
* made the escape filter 20% faster for happy path (escaping string for html with UTF-8)
* changed ☃ to § in tests
* enforced usage of named arguments after positional ones
* 1.12.3 (2013-04-08)
* fixed a security issue in the filesystem loader where it was possible to include a template one
level above the configured path
* fixed fatal error that should be an exception when adding a filter/function/test too late
* added a batch filter
* added support for encoding an array as query string in the url_encode filter
* 1.12.2 (2013-02-09)
* fixed the timezone used by the date filter and function when the given date contains a timezone (like 2010-01-28T15:00:00+02:00)
* fixed globals when getGlobals is called early on
* added the first and last filter
* 1.12.1 (2013-01-15)
* added support for object instances as the second argument of the constant function
* relaxed globals management to avoid a BC break
* added support for {{ some_string[:2] }}
* 1.12.0 (2013-01-08)
* added verbatim as an alias for the raw tag to avoid confusion with the raw filter
* fixed registration of tests and functions as anonymous functions
* fixed globals management
* 1.12.0-RC1 (2012-12-29)
* added an include function (does the same as the include tag but in a more flexible way)
* added the ability to use any PHP callable to define filters, functions, and tests
* added a syntax error when using a loop variable that is not defined
* added the ability to set default values for macro arguments
* added support for named arguments for filters, tests, and functions
* moved filters/functions/tests syntax errors to the parser
* added support for extended ternary operator syntaxes
* 1.11.1 (2012-11-11)
* fixed debug info line numbering (was off by 2)
* fixed escaping when calling a macro inside another one (regression introduced in 1.9.1)
* optimized variable access on PHP 5.4
* fixed a crash of the C extension when an exception was thrown from a macro called without being imported (using _self.XXX)
* 1.11.0 (2012-11-07)
* fixed macro compilation when a variable name is a PHP reserved keyword
* changed the date filter behavior to always apply the default timezone, except if false is passed as the timezone
* fixed bitwise operator precedences
* added the template_from_string function
* fixed default timezone usage for the date function
* optimized the way Twig exceptions are managed (to make them faster)
* added Twig_ExistsLoaderInterface (implementing this interface in your loader make the chain loader much faster)
* 1.10.3 (2012-10-19)
* fixed wrong template location in some error messages
* reverted a BC break introduced in 1.10.2
* added a split filter
* 1.10.2 (2012-10-15)
* fixed macro calls on PHP 5.4
* 1.10.1 (2012-10-15)
* made a speed optimization to macro calls when imported via the "import" tag
* fixed C extension compilation on Windows
* fixed a segfault in the C extension when using DateTime objects
* 1.10.0 (2012-09-28)
* extracted functional tests framework to make it reusable for third-party extensions
* added namespaced templates support in Twig_Loader_Filesystem
* added Twig_Loader_Filesystem::prependPath()
* fixed an error when a token parser pass a closure as a test to the subparse() method
* 1.9.2 (2012-08-25)
* fixed the in operator for objects that contain circular references
* fixed the C extension when accessing a public property of an object implementing the \ArrayAccess interface
* 1.9.1 (2012-07-22)
* optimized macro calls when auto-escaping is on
* fixed wrong parent class for Twig_Function_Node
* made Twig_Loader_Chain more explicit about problems
* 1.9.0 (2012-07-13)
* made the parsing independent of the template loaders
* fixed exception trace when an error occurs when rendering a child template
* added escaping strategies for CSS, URL, and HTML attributes
* fixed nested embed tag calls
* added the date_modify filter
* 1.8.3 (2012-06-17)
* fixed paths in the filesystem loader when passing a path that ends with a slash or a backslash
* fixed escaping when a project defines a function named html or js
* fixed chmod mode to apply the umask correctly
* 1.8.2 (2012-05-30)
* added the abs filter
* fixed a regression when using a number in template attributes
* fixed compiler when mbstring.func_overload is set to 2
* fixed DateTimeZone support in date filter
* 1.8.1 (2012-05-17)
* fixed a regression when dealing with SimpleXMLElement instances in templates
* fixed "is_safe" value for the "dump" function when "html_errors" is not defined in php.ini
* switched to use mbstring whenever possible instead of iconv (you might need to update your encoding as mbstring and iconv encoding names sometimes differ)
* 1.8.0 (2012-05-08)
* enforced interface when adding tests, filters, functions, and node visitors from extensions
* fixed a side-effect of the date filter where the timezone might be changed
* simplified usage of the autoescape tag; the only (optional) argument is now the escaping strategy or false (with a BC layer)
* added a way to dynamically change the auto-escaping strategy according to the template "filename"
* changed the autoescape option to also accept a supported escaping strategy (for BC, true is equivalent to html)
* added an embed tag
* 1.7.0 (2012-04-24)
* fixed a PHP warning when using CIFS
* fixed template line number in some exceptions
* added an iterable test
* added an error when defining two blocks with the same name in a template
* added the preserves_safety option for filters
* fixed a PHP notice when trying to access a key on a non-object/array variable
* enhanced error reporting when the template file is an instance of SplFileInfo
* added Twig_Environment::mergeGlobals()
* added compilation checks to avoid misuses of the sandbox tag
* fixed filesystem loader freshness logic for high traffic websites
* fixed random function when charset is null
* 1.6.5 (2012-04-11)
* fixed a regression when a template only extends another one without defining any blocks
* 1.6.4 (2012-04-02)
* fixed PHP notice in Twig_Error::guessTemplateLine() introduced in 1.6.3
* fixed performance when compiling large files
* optimized parent template creation when the template does not use dynamic inheritance
* 1.6.3 (2012-03-22)
* fixed usage of Z_ADDREF_P for PHP 5.2 in the C extension
* fixed compilation of numeric values used in templates when using a locale where the decimal separator is not a dot
* made the strategy used to guess the real template file name and line number in exception messages much faster and more accurate
* 1.6.2 (2012-03-18)
* fixed sandbox mode when used with inheritance
* added preserveKeys support for the slice filter
* fixed the date filter when a DateTime instance is passed with a specific timezone
* added a trim filter
* 1.6.1 (2012-02-29)
* fixed Twig C extension
* removed the creation of Twig_Markup instances when not needed
* added a way to set the default global timezone for dates
* fixed the slice filter on strings when the length is not specified
* fixed the creation of the cache directory in case of a race condition
* 1.6.0 (2012-02-04)
* fixed raw blocks when used with the whitespace trim option
* made a speed optimization to macro calls when imported via the "from" tag
* fixed globals, parsers, visitors, filters, tests, and functions management in Twig_Environment when a new one or new extension is added
* fixed the attribute function when passing arguments
* added slice notation support for the [] operator (syntactic sugar for the slice operator)
* added a slice filter
* added string support for the reverse filter
* fixed the empty test and the length filter for Twig_Markup instances
* added a date function to ease date comparison
* fixed unary operators precedence
* added recursive parsing support in the parser
* added string and integer handling for the random function
* 1.5.1 (2012-01-05)
* fixed a regression when parsing strings
* 1.5.0 (2012-01-04)
* added Traversable objects support for the join filter
* 1.5.0-RC2 (2011-12-30)
* added a way to set the default global date interval format
* fixed the date filter for DateInterval instances (setTimezone() does not exist for them)
* refactored Twig_Template::display() to ease its extension
* added a number_format filter
* 1.5.0-RC1 (2011-12-26)
* removed the need to quote hash keys
* allowed hash keys to be any expression
* added a do tag
* added a flush tag
* added support for dynamically named filters and functions
* added a dump function to help debugging templates
* added a nl2br filter
* added a random function
* added a way to change the default format for the date filter
* fixed the lexer when an operator ending with a letter ends a line
* added string interpolation support
* enhanced exceptions for unknown filters, functions, tests, and tags
* 1.4.0 (2011-12-07)
* fixed lexer when using big numbers (> PHP_INT_MAX)
* added missing preserveKeys argument to the reverse filter
* fixed macros containing filter tag calls
* 1.4.0-RC2 (2011-11-27)
* removed usage of Reflection in Twig_Template::getAttribute()
* added a C extension that can optionally replace Twig_Template::getAttribute()
* added negative timestamp support to the date filter
* 1.4.0-RC1 (2011-11-20)
* optimized variable access when using PHP 5.4
* changed the precedence of the .. operator to be more consistent with languages that implements such a feature like Ruby
* added an Exception to Twig_Loader_Array::isFresh() method when the template does not exist to be consistent with other loaders
* added Twig_Function_Node to allow more complex functions to have their own Node class
* added Twig_Filter_Node to allow more complex filters to have their own Node class
* added Twig_Test_Node to allow more complex tests to have their own Node class
* added a better error message when a template is empty but contain a BOM
* fixed "in" operator for empty strings
* fixed the "defined" test and the "default" filter (now works with more than one call (foo.bar.foo) and for both values of the strict_variables option)
* changed the way extensions are loaded (addFilter/addFunction/addGlobal/addTest/addNodeVisitor/addTokenParser/addExtension can now be called in any order)
* added Twig_Environment::display()
* made the escape filter smarter when the encoding is not supported by PHP
* added a convert_encoding filter
* moved all node manipulations outside the compile() Node method
* made several speed optimizations
* 1.3.0 (2011-10-08)
no changes
* 1.3.0-RC1 (2011-10-04)
* added an optimization for the parent() function
* added cache reloading when auto_reload is true and an extension has been modified
* added the possibility to force the escaping of a string already marked as safe (instance of Twig_Markup)
* allowed empty templates to be used as traits
* added traits support for the "parent" function
* 1.2.0 (2011-09-13)
no changes
* 1.2.0-RC1 (2011-09-10)
* enhanced the exception when a tag remains unclosed
* added support for empty Countable objects for the "empty" test
* fixed algorithm that determines if a template using inheritance is valid (no output between block definitions)
* added better support for encoding problems when escaping a string (available as of PHP 5.4)
* added a way to ignore a missing template when using the "include" tag ({% include "foo" ignore missing %})
* added support for an array of templates to the "include" and "extends" tags ({% include ['foo', 'bar'] %})
* added support for bitwise operators in expressions
* added the "attribute" function to allow getting dynamic attributes on variables
* added Twig_Loader_Chain
* added Twig_Loader_Array::setTemplate()
* added an optimization for the set tag when used to capture a large chunk of static text
* changed name regex to match PHP one "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" (works for blocks, tags, functions, filters, and macros)
* removed the possibility to use the "extends" tag from a block
* added "if" modifier support to "for" loops
* 1.1.2 (2011-07-30)
* fixed json_encode filter on PHP 5.2
* fixed regression introduced in 1.1.1 ({{ block(foo|lower) }})
* fixed inheritance when using conditional parents
* fixed compilation of templates when the body of a child template is not empty
* fixed output when a macro throws an exception
* fixed a parsing problem when a large chunk of text is enclosed in a comment tag
* added PHPDoc for all Token parsers and Core extension functions
* 1.1.1 (2011-07-17)
* added a performance optimization in the Optimizer (also helps to lower the number of nested level calls)
* made some performance improvement for some edge cases
* 1.1.0 (2011-06-28)
* fixed json_encode filter
* 1.1.0-RC3 (2011-06-24)
* fixed method case-sensitivity when using the sandbox mode
* added timezone support for the date filter
* fixed possible security problems with NUL bytes
* 1.1.0-RC2 (2011-06-16)
* added an exception when the template passed to "use" is not a string
* made 'a.b is defined' not throw an exception if a is not defined (in strict mode)
* added {% line \d+ %} directive
* 1.1.0-RC1 (2011-05-28)
Flush your cache after upgrading.
* fixed date filter when using a timestamp
* fixed the defined test for some cases
* fixed a parsing problem when a large chunk of text is enclosed in a raw tag
* added support for horizontal reuse of template blocks (see docs for more information)
* added whitespace control modifier to all tags (see docs for more information)
* added null as an alias for none (the null test is also an alias for the none test now)
* made TRUE, FALSE, NONE equivalent to their lowercase counterparts
* wrapped all compilation and runtime exceptions with Twig_Error_Runtime and added logic to guess the template name and line
* moved display() method to Twig_Template (generated templates should now use doDisplay() instead)
* 1.0.0 (2011-03-27)
* fixed output when using mbstring
* fixed duplicate call of methods when using the sandbox
* made the charset configurable for the escape filter
* 1.0.0-RC2 (2011-02-21)
* changed the way {% set %} works when capturing (the content is now marked as safe)
* added support for macro name in the endmacro tag
* make Twig_Error compatible with PHP 5.3.0 >
* fixed an infinite loop on some Windows configurations
* fixed the "length" filter for numbers
* fixed Template::getAttribute() as properties in PHP are case sensitive
* removed coupling between Twig_Node and Twig_Template
* fixed the ternary operator precedence rule
* 1.0.0-RC1 (2011-01-09)
Backward incompatibilities:
* the "items" filter, which has been deprecated for quite a long time now, has been removed
* the "range" filter has been converted to a function: 0|range(10) -> range(0, 10)
* the "constant" filter has been converted to a function: {{ some_date|date('DATE_W3C'|constant) }} -> {{ some_date|date(constant('DATE_W3C')) }}
* the "cycle" filter has been converted to a function: {{ ['odd', 'even']|cycle(i) }} -> {{ cycle(['odd', 'even'], i) }}
* the "for" tag does not support "joined by" anymore
* the "autoescape" first argument is now "true"/"false" (instead of "on"/"off")
* the "parent" tag has been replaced by a "parent" function ({{ parent() }} instead of {% parent %})
* the "display" tag has been replaced by a "block" function ({{ block('title') }} instead of {% display title %})
* removed the grammar and simple token parser (moved to the Twig Extensions repository)
Changes:
* added "needs_context" option for filters and functions (the context is then passed as a first argument)
* added global variables support
* made macros return their value instead of echoing directly (fixes calling a macro in sandbox mode)
* added the "from" tag to import macros as functions
* added support for functions (a function is just syntactic sugar for a getAttribute() call)
* made macros callable when sandbox mode is enabled
* added an exception when a macro uses a reserved name
* the "default" filter now uses the "empty" test instead of just checking for null
* added the "empty" test
* 0.9.10 (2010-12-16)
Backward incompatibilities:
* The Escaper extension is enabled by default, which means that all displayed
variables are now automatically escaped. You can revert to the previous
behavior by removing the extension via $env->removeExtension('escaper')
or just set the 'autoescape' option to 'false'.
* removed the "without loop" attribute for the "for" tag (not needed anymore
as the Optimizer take care of that for most cases)
* arrays and hashes have now a different syntax
* arrays keep the same syntax with square brackets: [1, 2]
* hashes now use curly braces (["a": "b"] should now be written as {"a": "b"})
* support for "arrays with keys" and "hashes without keys" is not supported anymore ([1, "foo": "bar"] or {"foo": "bar", 1})
* the i18n extension is now part of the Twig Extensions repository
Changes:
* added the merge filter
* removed 'is_escaper' option for filters (a left over from the previous version) -- you must use 'is_safe' now instead
* fixed usage of operators as method names (like is, in, and not)
* changed the order of execution for node visitors
* fixed default() filter behavior when used with strict_variables set to on
* fixed filesystem loader compatibility with PHAR files
* enhanced error messages when an unexpected token is parsed in an expression
* fixed filename not being added to syntax error messages
* added the autoescape option to enable/disable autoescaping
* removed the newline after a comment (mimics PHP behavior)
* added a syntax error exception when parent block is used on a template that does not extend another one
* made the Escaper extension enabled by default
* fixed sandbox extension when used with auto output escaping
* fixed escaper when wrapping a Twig_Node_Print (the original class must be preserved)
* added an Optimizer extension (enabled by default; optimizes "for" loops and "raw" filters)
* added priority to node visitors
* 0.9.9 (2010-11-28)
Backward incompatibilities:
* the self special variable has been renamed to _self
* the odd and even filters are now tests:
{{ foo|odd }} must now be written {{ foo is odd }}
* the "safe" filter has been renamed to "raw"
* in Node classes,
sub-nodes are now accessed via getNode() (instead of property access)
attributes via getAttribute() (instead of array access)
* the urlencode filter had been renamed to url_encode
* the include tag now merges the passed variables with the current context by default
(the old behavior is still possible by adding the "only" keyword)
* moved Exceptions to Twig_Error_* (Twig_SyntaxError/Twig_RuntimeError are now Twig_Error_Syntax/Twig_Error_Runtime)
* removed support for {{ 1 < i < 3 }} (use {{ i > 1 and i < 3 }} instead)
* the "in" filter has been removed ({{ a|in(b) }} should now be written {{ a in b }})
Changes:
* added file and line to Twig_Error_Runtime exceptions thrown from Twig_Template
* changed trans tag to accept any variable for the plural count
* fixed sandbox mode (__toString() method check was not enforced if called implicitly from complex statements)
* added the ** (power) operator
* changed the algorithm used for parsing expressions
* added the spaceless tag
* removed trim_blocks option
* added support for is*() methods for attributes (foo.bar now looks for foo->getBar() or foo->isBar())
* changed all exceptions to extend Twig_Error
* fixed unary expressions ({{ not(1 or 0) }})
* fixed child templates (with an extend tag) that uses one or more imports
* added support for {{ 1 not in [2, 3] }} (more readable than the current {{ not (1 in [2, 3]) }})
* escaping has been rewritten
* the implementation of template inheritance has been rewritten
(blocks can now be called individually and still work with inheritance)
* fixed error handling for if tag when a syntax error occurs within a subparse process
* added a way to implement custom logic for resolving token parsers given a tag name
* fixed js escaper to be stricter (now uses a whilelist-based js escaper)
* added the following filers: "constant", "trans", "replace", "json_encode"
* added a "constant" test
* fixed objects with __toString() not being autoescaped
* fixed subscript expressions when calling __call() (methods now keep the case)
* added "test" feature (accessible via the "is" operator)
* removed the debug tag (should be done in an extension)
* fixed trans tag when no vars are used in plural form
* fixed race condition when writing template cache
* added the special _charset variable to reference the current charset
* added the special _context variable to reference the current context
* renamed self to _self (to avoid conflict)
* fixed Twig_Template::getAttribute() for protected properties
* 0.9.8 (2010-06-28)
Backward incompatibilities:
* the trans tag plural count is now attached to the plural tag:
old: `{% trans count %}...{% plural %}...{% endtrans %}`
new: `{% trans %}...{% plural count %}...{% endtrans %}`
* added a way to translate strings coming from a variable ({% trans var %})
* fixed trans tag when used with the Escaper extension
* fixed default cache umask
* removed Twig_Template instances from the debug tag output
* fixed objects with __isset() defined
* fixed set tag when used with a capture
* fixed type hinting for Twig_Environment::addFilter() method
* 0.9.7 (2010-06-12)
Backward incompatibilities:
* changed 'as' to '=' for the set tag ({% set title as "Title" %} must now be {% set title = "Title" %})
* removed the sandboxed attribute of the include tag (use the new sandbox tag instead)
* refactored the Node system (if you have custom nodes, you will have to update them to use the new API)
* added self as a special variable that refers to the current template (useful for importing macros from the current template)
* added Twig_Template instance support to the include tag
* added support for dynamic and conditional inheritance ({% extends some_var %} and {% extends standalone ? "minimum" : "base" %})
* added a grammar sub-framework to ease the creation of custom tags
* fixed the for tag for large arrays (some loop variables are now only available for arrays and objects that implement the Countable interface)
* removed the Twig_Resource::resolveMissingFilter() method
* fixed the filter tag which did not apply filtering to included files
* added a bunch of unit tests
* added a bunch of phpdoc
* added a sandbox tag in the sandbox extension
* changed the date filter to support any date format supported by DateTime
* added strict_variable setting to throw an exception when an invalid variable is used in a template (disabled by default)
* added the lexer, parser, and compiler as arguments to the Twig_Environment constructor
* changed the cache option to only accepts an explicit path to a cache directory or false
* added a way to add token parsers, filters, and visitors without creating an extension
* added three interfaces: Twig_NodeInterface, Twig_TokenParserInterface, and Twig_FilterInterface
* changed the generated code to match the new coding standards
* fixed sandbox mode (__toString() method check was not enforced if called implicitly from a simple statement like {{ article }})
* added an exception when a child template has a non-empty body (as it is always ignored when rendering)
* 0.9.6 (2010-05-12)
* fixed variables defined outside a loop and for which the value changes in a for loop
* fixed the test suite for PHP 5.2 and older versions of PHPUnit
* added support for __call() in expression resolution
* fixed node visiting for macros (macros are now visited by visitors as any other node)
* fixed nested block definitions with a parent call (rarely useful but nonetheless supported now)
* added the cycle filter
* fixed the Lexer when mbstring.func_overload is used with an mbstring.internal_encoding different from ASCII
* added a long-syntax for the set tag ({% set foo %}...{% endset %})
* unit tests are now powered by PHPUnit
* added support for gettext via the `i18n` extension
* fixed twig_capitalize_string_filter() and fixed twig_length_filter() when used with UTF-8 values
* added a more useful exception if an if tag is not closed properly
* added support for escaping strategy in the autoescape tag
* fixed lexer when a template has a big chunk of text between/in a block
* 0.9.5 (2010-01-20)
As for any new release, don't forget to remove all cached templates after
upgrading.
If you have defined custom filters, you MUST upgrade them for this release. To
upgrade, replace "array" with "new Twig_Filter_Function", and replace the
environment constant by the "needs_environment" option:
// before
'even' => array('twig_is_even_filter', false),
'escape' => array('twig_escape_filter', true),
// after
'even' => new Twig_Filter_Function('twig_is_even_filter'),
'escape' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true)),
If you have created NodeTransformer classes, you will need to upgrade them to
the new interface (please note that the interface is not yet considered
stable).
* fixed list nodes that did not extend the Twig_NodeListInterface
* added the "without loop" option to the for tag (it disables the generation of the loop variable)
* refactored node transformers to node visitors
* fixed automatic-escaping for blocks
* added a way to specify variables to pass to an included template
* changed the automatic-escaping rules to be more sensible and more configurable in custom filters (the documentation lists all the rules)
* improved the filter system to allow object methods to be used as filters
* changed the Array and String loaders to actually make use of the cache mechanism
* included the default filter function definitions in the extension class files directly (Core, Escaper)
* added the // operator (like the floor() PHP function)
* added the .. operator (as a syntactic sugar for the range filter when the step is 1)
* added the in operator (as a syntactic sugar for the in filter)
* added the following filters in the Core extension: in, range
* added support for arrays (same behavior as in PHP, a mix between lists and dictionaries, arrays and hashes)
* enhanced some error messages to provide better feedback in case of parsing errors
* 0.9.4 (2009-12-02)
If you have custom loaders, you MUST upgrade them for this release: The
Twig_Loader base class has been removed, and the Twig_LoaderInterface has also
been changed (see the source code for more information or the documentation).
* added support for DateTime instances for the date filter
* fixed loop.last when the array only has one item
* made it possible to insert newlines in tag and variable blocks
* fixed a bug when a literal '\n' were present in a template text
* fixed bug when the filename of a template contains */
* refactored loaders
* 0.9.3 (2009-11-11)
This release is NOT backward compatible with the previous releases.
The loaders do not take the cache and autoReload arguments anymore. Instead,
the Twig_Environment class has two new options: cache and auto_reload.
Upgrading your code means changing this kind of code:
$loader = new Twig_Loader_Filesystem('/path/to/templates', '/path/to/compilation_cache', true);
$twig = new Twig_Environment($loader);
to something like this:
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
'auto_reload' => true,
));
* deprecated the "items" filter as it is not needed anymore
* made cache and auto_reload options of Twig_Environment instead of arguments of Twig_Loader
* optimized template loading speed
* removed output when an error occurs in a template and render() is used
* made major speed improvements for loops (up to 300% on even the smallest loops)
* added properties as part of the sandbox mode
* added public properties support (obj.item can now be the item property on the obj object)
* extended set tag to support expression as value ({% set foo as 'foo' ~ 'bar' %} )
* fixed bug when \ was used in HTML
* 0.9.2 (2009-10-29)
* made some speed optimizations
* changed the cache extension to .php
* added a js escaping strategy
* added support for short block tag
* changed the filter tag to allow chained filters
* made lexer more flexible as you can now change the default delimiters
* added set tag
* changed default directory permission when cache dir does not exist (more secure)
* added macro support
* changed filters first optional argument to be a Twig_Environment instance instead of a Twig_Template instance
* made Twig_Autoloader::autoload() a static method
* avoid writing template file if an error occurs
* added $ escaping when outputting raw strings
* enhanced some error messages to ease debugging
* fixed empty cache files when the template contains an error
* 0.9.1 (2009-10-14)
* fixed a bug in PHP 5.2.6
* fixed numbers with one than one decimal
* added support for method calls with arguments ({{ foo.bar('a', 43) }})
* made small speed optimizations
* made minor tweaks to allow better extensibility and flexibility
* 0.9.0 (2009-10-12)
* Initial release
php-twig-2.12.5/LICENSE 0000664 0000000 0000000 00000002702 13624573447 0014365 0 ustar 00root root 0000000 0000000 Copyright (c) 2009-2020 by the Twig Team.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* The names of the contributors may not be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
php-twig-2.12.5/README.rst 0000664 0000000 0000000 00000001442 13624573447 0015047 0 ustar 00root root 0000000 0000000 Twig, the flexible, fast, and secure template language for PHP
==============================================================
Twig is a template language for PHP, released under the new BSD license (code
and documentation).
Twig uses a syntax similar to the Django and Jinja template languages which
inspired the Twig runtime environment.
Sponsors
--------
.. raw:: html
More Information
----------------
Read the `documentation`_ for more information.
.. _documentation: https://twig.symfony.com/documentation
php-twig-2.12.5/composer.json 0000664 0000000 0000000 00000002376 13624573447 0016111 0 ustar 00root root 0000000 0000000 {
"name": "twig/twig",
"type": "library",
"description": "Twig, the flexible, fast, and secure template language for PHP",
"keywords": ["templating"],
"homepage": "https://twig.symfony.com",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Twig Team",
"role": "Contributors"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com",
"role": "Project Founder"
}
],
"require": {
"php": "^7.0",
"symfony/polyfill-mbstring": "^1.3",
"symfony/polyfill-ctype": "^1.8"
},
"require-dev": {
"symfony/phpunit-bridge": "^4.4|^5.0",
"psr/container": "^1.0"
},
"autoload": {
"psr-0" : {
"Twig_" : "lib/"
},
"psr-4" : {
"Twig\\" : "src/"
}
},
"autoload-dev": {
"psr-4" : {
"Twig\\Tests\\" : "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "2.12-dev"
}
}
}
php-twig-2.12.5/doc/ 0000775 0000000 0000000 00000000000 13624573447 0014124 5 ustar 00root root 0000000 0000000 php-twig-2.12.5/doc/advanced.rst 0000664 0000000 0000000 00000067123 13624573447 0016434 0 ustar 00root root 0000000 0000000 Extending Twig
==============
Twig can be extended in many ways; you can add extra tags, filters, tests,
operators, global variables, and functions. You can even extend the parser
itself with node visitors.
.. note::
The first section of this chapter describes how to extend Twig. If you want
to reuse your changes in different projects or if you want to share them
with others, you should then create an extension as described in the
following section.
.. caution::
When extending Twig without creating an extension, Twig won't be able to
recompile your templates when the PHP code is updated. To see your changes
in real-time, either disable template caching or package your code into an
extension (see the next section of this chapter).
Before extending Twig, you must understand the differences between all the
different possible extension points and when to use them.
First, remember that Twig has two main language constructs:
* ``{{ }}``: used to print the result of an expression evaluation;
* ``{% %}``: used to execute statements.
To understand why Twig exposes so many extension points, let's see how to
implement a *Lorem ipsum* generator (it needs to know the number of words to
generate).
You can use a ``lipsum`` *tag*:
.. code-block:: twig
{% lipsum 40 %}
That works, but using a tag for ``lipsum`` is not a good idea for at least
three main reasons:
* ``lipsum`` is not a language construct;
* The tag outputs something;
* The tag is not flexible as you cannot use it in an expression:
.. code-block:: twig
{{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
In fact, you rarely need to create tags; and that's good news because tags are
the most complex extension point.
Now, let's use a ``lipsum`` *filter*:
.. code-block:: twig
{{ 40|lipsum }}
Again, it works. But a filter should transform the passed value to something
else. Here, we use the value to indicate the number of words to generate (so,
``40`` is an argument of the filter, not the value we want to transform).
Next, let's use a ``lipsum`` *function*:
.. code-block:: twig
{{ lipsum(40) }}
Here we go. For this specific example, the creation of a function is the
extension point to use. And you can use it anywhere an expression is accepted:
.. code-block:: twig
{{ 'some text' ~ lipsum(40) ~ 'some more text' }}
{% set lipsum = lipsum(40) %}
Lastly, you can also use a *global* object with a method able to generate lorem
ipsum text:
.. code-block:: twig
{{ text.lipsum(40) }}
As a rule of thumb, use functions for frequently used features and global
objects for everything else.
Keep in mind the following when you want to extend Twig:
========== ========================== ========== =========================
What? Implementation difficulty? How often? When?
========== ========================== ========== =========================
*macro* simple frequent Content generation
*global* simple frequent Helper object
*function* simple frequent Content generation
*filter* simple frequent Value transformation
*tag* complex rare DSL language construct
*test* simple rare Boolean decision
*operator* simple rare Values transformation
========== ========================== ========== =========================
Globals
-------
A global variable is like any other template variable, except that it's
available in all templates and macros::
$twig = new \Twig\Environment($loader);
$twig->addGlobal('text', new Text());
You can then use the ``text`` variable anywhere in a template:
.. code-block:: twig
{{ text.lipsum(40) }}
Filters
-------
Creating a filter consists of associating a name with a PHP callable::
// an anonymous function
$filter = new \Twig\TwigFilter('rot13', function ($string) {
return str_rot13($string);
});
// or a simple PHP function
$filter = new \Twig\TwigFilter('rot13', 'str_rot13');
// or a class static method
$filter = new \Twig\TwigFilter('rot13', ['SomeClass', 'rot13Filter']);
$filter = new \Twig\TwigFilter('rot13', 'SomeClass::rot13Filter');
// or a class method
$filter = new \Twig\TwigFilter('rot13', [$this, 'rot13Filter']);
// the one below needs a runtime implementation (see below for more information)
$filter = new \Twig\TwigFilter('rot13', ['SomeClass', 'rot13Filter']);
The first argument passed to the ``\Twig\TwigFilter`` constructor is the name of the
filter you will use in templates and the second one is the PHP callable to
associate with it.
Then, add the filter to the Twig environment::
$twig = new \Twig\Environment($loader);
$twig->addFilter($filter);
And here is how to use it in a template:
.. code-block:: twig
{{ 'Twig'|rot13 }}
{# will output Gjvt #}
When called by Twig, the PHP callable receives the left side of the filter
(before the pipe ``|``) as the first argument and the extra arguments passed
to the filter (within parentheses ``()``) as extra arguments.
For instance, the following code:
.. code-block:: twig
{{ 'TWIG'|lower }}
{{ now|date('d/m/Y') }}
is compiled to something like the following::
The ``\Twig\TwigFilter`` class takes an array of options as its last argument::
$filter = new \Twig\TwigFilter('rot13', 'str_rot13', $options);
Environment-aware Filters
~~~~~~~~~~~~~~~~~~~~~~~~~
If you want to access the current environment instance in your filter, set the
``needs_environment`` option to ``true``; Twig will pass the current
environment as the first argument to the filter call::
$filter = new \Twig\TwigFilter('rot13', function (Twig_Environment $env, $string) {
// get the current charset for instance
$charset = $env->getCharset();
return str_rot13($string);
}, ['needs_environment' => true]);
Context-aware Filters
~~~~~~~~~~~~~~~~~~~~~
If you want to access the current context in your filter, set the
``needs_context`` option to ``true``; Twig will pass the current context as
the first argument to the filter call (or the second one if
``needs_environment`` is also set to ``true``)::
$filter = new \Twig\TwigFilter('rot13', function ($context, $string) {
// ...
}, ['needs_context' => true]);
$filter = new \Twig\TwigFilter('rot13', function (Twig_Environment $env, $context, $string) {
// ...
}, ['needs_context' => true, 'needs_environment' => true]);
Automatic Escaping
~~~~~~~~~~~~~~~~~~
If automatic escaping is enabled, the output of the filter may be escaped
before printing. If your filter acts as an escaper (or explicitly outputs HTML
or JavaScript code), you will want the raw output to be printed. In such a
case, set the ``is_safe`` option::
$filter = new \Twig\TwigFilter('nl2br', 'nl2br', ['is_safe' => ['html']]);
Some filters may need to work on input that is already escaped or safe, for
example when adding (safe) HTML tags to originally unsafe output. In such a
case, set the ``pre_escape`` option to escape the input data before it is run
through your filter::
$filter = new \Twig\TwigFilter('somefilter', 'somefilter', ['pre_escape' => 'html', 'is_safe' => ['html']]);
Variadic Filters
~~~~~~~~~~~~~~~~
When a filter should accept an arbitrary number of arguments, set the
``is_variadic`` option to ``true``; Twig will pass the extra arguments as the
last argument to the filter call as an array::
$filter = new \Twig\TwigFilter('thumbnail', function ($file, array $options = []) {
// ...
}, ['is_variadic' => true]);
Be warned that :ref:`named arguments ` passed to a variadic
filter cannot be checked for validity as they will automatically end up in the
option array.
Dynamic Filters
~~~~~~~~~~~~~~~
A filter name containing the special ``*`` character is a dynamic filter and
the ``*`` part will match any string::
$filter = new \Twig\TwigFilter('*_path', function ($name, $arguments) {
// ...
});
The following filters are matched by the above defined dynamic filter:
* ``product_path``
* ``category_path``
A dynamic filter can define more than one dynamic parts::
$filter = new \Twig\TwigFilter('*_path_*', function ($name, $suffix, $arguments) {
// ...
});
The filter receives all dynamic part values before the normal filter arguments,
but after the environment and the context. For instance, a call to
``'foo'|a_path_b()`` will result in the following arguments to be passed to the
filter: ``('a', 'b', 'foo')``.
Deprecated Filters
~~~~~~~~~~~~~~~~~~
You can mark a filter as being deprecated by setting the ``deprecated`` option
to ``true``. You can also give an alternative filter that replaces the
deprecated one when that makes sense::
$filter = new \Twig\TwigFilter('obsolete', function () {
// ...
}, ['deprecated' => true, 'alternative' => 'new_one']);
When a filter is deprecated, Twig emits a deprecation notice when compiling a
template using it. See :ref:`deprecation-notices` for more information.
Functions
---------
Functions are defined in the exact same way as filters, but you need to create
an instance of ``\Twig\TwigFunction``::
$twig = new \Twig\Environment($loader);
$function = new \Twig\TwigFunction('function_name', function () {
// ...
});
$twig->addFunction($function);
Functions support the same features as filters, except for the ``pre_escape``
and ``preserves_safety`` options.
Tests
-----
Tests are defined in the exact same way as filters and functions, but you need
to create an instance of ``\Twig\TwigTest``::
$twig = new \Twig\Environment($loader);
$test = new \Twig\TwigTest('test_name', function () {
// ...
});
$twig->addTest($test);
Tests allow you to create custom application specific logic for evaluating
boolean conditions. As a simple example, let's create a Twig test that checks if
objects are 'red'::
$twig = new \Twig\Environment($loader);
$test = new \Twig\TwigTest('red', function ($value) {
if (isset($value->color) && $value->color == 'red') {
return true;
}
if (isset($value->paint) && $value->paint == 'red') {
return true;
}
return false;
});
$twig->addTest($test);
Test functions must always return ``true``/``false``.
When creating tests you can use the ``node_class`` option to provide custom test
compilation. This is useful if your test can be compiled into PHP primitives.
This is used by many of the tests built into Twig::
$twig = new \Twig\Environment($loader);
$test = new \Twig\TwigTest(
'odd',
null,
['node_class' => \Twig\Node\Expression\Test\OddTest::class]);
$twig->addTest($test);
class Twig_Node_Expression_Test_Odd extends \Twig\Node\Expression\TestExpression
{
public function compile(\Twig\Compiler $compiler)
{
$compiler
->raw('(')
->subcompile($this->getNode('node'))
->raw(' % 2 == 1')
->raw(')')
;
}
}
The above example shows how you can create tests that use a node class. The node
class has access to one sub-node called ``node``. This sub-node contains the
value that is being tested. When the ``odd`` filter is used in code such as:
.. code-block:: twig
{% if my_value is odd %}
The ``node`` sub-node will contain an expression of ``my_value``. Node-based
tests also have access to the ``arguments`` node. This node will contain the
various other arguments that have been provided to your test.
.. versionadded:: 2.6
Dynamic tests support was added in Twig 2.6.
If you want to pass a variable number of positional or named arguments to the
test, set the ``is_variadic`` option to ``true``. Tests support dynamic
names (see dynamic filters for the syntax).
Tags
----
One of the most exciting features of a template engine like Twig is the
possibility to define new **language constructs**. This is also the most complex
feature as you need to understand how Twig's internals work.
Most of the time though, a tag is not needed:
* If your tag generates some output, use a **function** instead.
* If your tag modifies some content and returns it, use a **filter** instead.
For instance, if you want to create a tag that converts a Markdown formatted
text to HTML, create a ``markdown`` filter instead:
.. code-block:: twig
{{ '**markdown** text'|markdown }}
If you want use this filter on large amounts of text, wrap it with the
:doc:`apply ` tag:
.. code-block:: twig
{% apply markdown %}
Title
=====
Much better than creating a tag as you can **compose** filters.
{% endapply %}
.. note::
The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with
previous versions.
* If your tag does not output anything, but only exists because of a side
effect, create a **function** that returns nothing and call it via the
:doc:`filter ` tag.
For instance, if you want to create a tag that logs text, create a ``log``
function instead and call it via the :doc:`do ` tag:
.. code-block:: twig
{% do log('Log some things') %}
If you still want to create a tag for a new language construct, great!
Let's create a ``set`` tag that allows the definition of simple variables from
within a template. The tag can be used like follows:
.. code-block:: twig
{% set name = "value" %}
{{ name }}
{# should output value #}
.. note::
The ``set`` tag is part of the Core extension and as such is always
available. The built-in version is slightly more powerful and supports
multiple assignments by default.
Three steps are needed to define a new tag:
* Defining a Token Parser class (responsible for parsing the template code);
* Defining a Node class (responsible for converting the parsed code to PHP);
* Registering the tag.
Registering a new tag
~~~~~~~~~~~~~~~~~~~~~
Add a tag by calling the ``addTokenParser`` method on the ``\Twig\Environment``
instance::
$twig = new \Twig\Environment($loader);
$twig->addTokenParser(new Project_Set_TokenParser());
Defining a Token Parser
~~~~~~~~~~~~~~~~~~~~~~~
Now, let's see the actual code of this class::
class Project_Set_TokenParser extends \Twig\TokenParser\AbstractTokenParser
{
public function parse(\Twig\Token $token)
{
$parser = $this->parser;
$stream = $parser->getStream();
$name = $stream->expect(\Twig\Token::NAME_TYPE)->getValue();
$stream->expect(\Twig\Token::OPERATOR_TYPE, '=');
$value = $parser->getExpressionParser()->parseExpression();
$stream->expect(\Twig\Token::BLOCK_END_TYPE);
return new Project_Set_Node($name, $value, $token->getLine(), $this->getTag());
}
public function getTag()
{
return 'set';
}
}
The ``getTag()`` method must return the tag we want to parse, here ``set``.
The ``parse()`` method is invoked whenever the parser encounters a ``set``
tag. It should return a ``\Twig\Node\Node`` instance that represents the node (the
``Project_Set_Node`` calls creating is explained in the next section).
The parsing process is simplified thanks to a bunch of methods you can call
from the token stream (``$this->parser->getStream()``):
* ``getCurrent()``: Gets the current token in the stream.
* ``next()``: Moves to the next token in the stream, *but returns the old one*.
* ``test($type)``, ``test($value)`` or ``test($type, $value)``: Determines whether
the current token is of a particular type or value (or both). The value may be an
array of several possible values.
* ``expect($type[, $value[, $message]])``: If the current token isn't of the given
type/value a syntax error is thrown. Otherwise, if the type and value are correct,
the token is returned and the stream moves to the next token.
* ``look()``: Looks at the next token without consuming it.
Parsing expressions is done by calling the ``parseExpression()`` like we did for
the ``set`` tag.
.. tip::
Reading the existing ``TokenParser`` classes is the best way to learn all
the nitty-gritty details of the parsing process.
Defining a Node
~~~~~~~~~~~~~~~
The ``Project_Set_Node`` class itself is quite short::
class Project_Set_Node extends \Twig\Node\Node
{
public function __construct($name, \Twig\Node\Expression\AbstractExpression $value, $line, $tag = null)
{
parent::__construct(['value' => $value], ['name' => $name], $line, $tag);
}
public function compile(\Twig\Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('$context[\''.$this->getAttribute('name').'\'] = ')
->subcompile($this->getNode('value'))
->raw(";\n")
;
}
}
The compiler implements a fluid interface and provides methods that helps the
developer generate beautiful and readable PHP code:
* ``subcompile()``: Compiles a node.
* ``raw()``: Writes the given string as is.
* ``write()``: Writes the given string by adding indentation at the beginning
of each line.
* ``string()``: Writes a quoted string.
* ``repr()``: Writes a PHP representation of a given value (see
``\Twig\Node\ForNode`` for a usage example).
* ``addDebugInfo()``: Adds the line of the original template file related to
the current node as a comment.
* ``indent()``: Indents the generated code (see ``\Twig\Node\BlockNode`` for a
usage example).
* ``outdent()``: Outdents the generated code (see ``\Twig\Node\BlockNode`` for a
usage example).
.. _creating_extensions:
Creating an Extension
---------------------
The main motivation for writing an extension is to move often used code into a
reusable class like adding support for internationalization. An extension can
define tags, filters, tests, operators, functions, and node visitors.
Most of the time, it is useful to create a single extension for your project,
to host all the specific tags and filters you want to add to Twig.
.. tip::
When packaging your code into an extension, Twig is smart enough to
recompile your templates whenever you make a change to it (when
``auto_reload`` is enabled).
An extension is a class that implements the following interface::
interface \Twig\Extension\ExtensionInterface
{
/**
* Returns the token parser instances to add to the existing list.
*
* @return \Twig\TokenParser\TokenParserInterface[]
*/
public function getTokenParsers();
/**
* Returns the node visitor instances to add to the existing list.
*
* @return \Twig\NodeVisitor\NodeVisitorInterface[]
*/
public function getNodeVisitors();
/**
* Returns a list of filters to add to the existing list.
*
* @return \Twig\TwigFilter[]
*/
public function getFilters();
/**
* Returns a list of tests to add to the existing list.
*
* @return \Twig\TwigTest[]
*/
public function getTests();
/**
* Returns a list of functions to add to the existing list.
*
* @return \Twig\TwigFunction[]
*/
public function getFunctions();
/**
* Returns a list of operators to add to the existing list.
*
* @return array First array of unary operators, second array of binary operators
*/
public function getOperators();
}
To keep your extension class clean and lean, inherit from the built-in
``\Twig\Extension\AbstractExtension`` class instead of implementing the interface as it provides
empty implementations for all methods::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
}
This extension does nothing for now. We will customize it in the next sections.
You can save your extension anywhere on the filesystem, as all extensions must
be registered explicitly to be available in your templates.
You can register an extension by using the ``addExtension()`` method on your
main ``Environment`` object::
$twig = new \Twig\Environment($loader);
$twig->addExtension(new Project_Twig_Extension());
.. tip::
The Twig core extensions are great examples of how extensions work.
Globals
~~~~~~~
Global variables can be registered in an extension via the ``getGlobals()``
method::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension implements \Twig\Extension\GlobalsInterface
{
public function getGlobals()
{
return [
'text' => new Text(),
];
}
// ...
}
Functions
~~~~~~~~~
Functions can be registered in an extension via the ``getFunctions()``
method::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getFunctions()
{
return [
new \Twig\TwigFunction('lipsum', 'generate_lipsum'),
];
}
// ...
}
Filters
~~~~~~~
To add a filter to an extension, you need to override the ``getFilters()``
method. This method must return an array of filters to add to the Twig
environment::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getFilters()
{
return [
new \Twig\TwigFilter('rot13', 'str_rot13'),
];
}
// ...
}
Tags
~~~~
Adding a tag in an extension can be done by overriding the
``getTokenParsers()`` method. This method must return an array of tags to add
to the Twig environment::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getTokenParsers()
{
return [new Project_Set_TokenParser()];
}
// ...
}
In the above code, we have added a single new tag, defined by the
``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is
responsible for parsing the tag and compiling it to PHP.
Operators
~~~~~~~~~
The ``getOperators()`` methods lets you add new operators. Here is how to add
the ``!``, ``||``, and ``&&`` operators::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getOperators()
{
return [
[
'!' => ['precedence' => 50, 'class' => \Twig\Node\Expression\Unary\NotUnary::class],
],
[
'||' => ['precedence' => 10, 'class' => \Twig\Node\Expression\Binary\OrBinary::class, 'associativity' => \Twig\ExpressionParser::OPERATOR_LEFT],
'&&' => ['precedence' => 15, 'class' => \Twig\Node\Expression\Binary\AndBinary::class, 'associativity' => \Twig\ExpressionParser::OPERATOR_LEFT],
],
];
}
// ...
}
Tests
~~~~~
The ``getTests()`` method lets you add new test functions::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getTests()
{
return [
new \Twig\TwigTest('even', 'twig_test_even'),
];
}
// ...
}
Definition vs Runtime
~~~~~~~~~~~~~~~~~~~~~
Twig filters, functions, and tests runtime implementations can be defined as
any valid PHP callable:
* **functions/static methods**: Simple to implement and fast (used by all Twig
core extensions); but it is hard for the runtime to depend on external
objects;
* **closures**: Simple to implement;
* **object methods**: More flexible and required if your runtime code depends
on external objects.
The simplest way to use methods is to define them on the extension itself::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function getFunctions()
{
return [
new \Twig\TwigFunction('rot13', [$this, 'rot13']),
];
}
public function rot13($value)
{
return $this->rot13Provider->rot13($value);
}
}
This is very convenient but not recommended as it makes template compilation
depend on runtime dependencies even if they are not needed (think for instance
as a dependency that connects to a database engine).
You can decouple the extension definitions from their runtime implementations by
registering a ``\Twig\RuntimeLoader\RuntimeLoaderInterface`` instance on the
environment that knows how to instantiate such runtime classes (runtime classes
must be autoload-able)::
class RuntimeLoader implements \Twig\RuntimeLoader\RuntimeLoaderInterface
{
public function load($class)
{
// implement the logic to create an instance of $class
// and inject its dependencies
// most of the time, it means using your dependency injection container
if ('Project_Twig_RuntimeExtension' === $class) {
return new $class(new Rot13Provider());
} else {
// ...
}
}
}
$twig->addRuntimeLoader(new RuntimeLoader());
.. note::
Twig comes with a PSR-11 compatible runtime loader
(``\Twig\RuntimeLoader\ContainerRuntimeLoader``).
It is now possible to move the runtime logic to a new
``Project_Twig_RuntimeExtension`` class and use it directly in the extension::
class Project_Twig_RuntimeExtension
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function rot13($value)
{
return $this->rot13Provider->rot13($value);
}
}
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
public function getFunctions()
{
return [
new \Twig\TwigFunction('rot13', ['Project_Twig_RuntimeExtension', 'rot13']),
// or
new \Twig\TwigFunction('rot13', 'Project_Twig_RuntimeExtension::rot13'),
];
}
}
Testing an Extension
--------------------
Functional Tests
~~~~~~~~~~~~~~~~
You can create functional tests for extensions by creating the following file
structure in your test directory::
Fixtures/
filters/
foo.test
bar.test
functions/
foo.test
bar.test
tags/
foo.test
bar.test
IntegrationTest.php
The ``IntegrationTest.php`` file should look like this::
class Project_Tests_IntegrationTest extends \Twig\Test\IntegrationTestCase
{
public function getExtensions()
{
return [
new Project_Twig_Extension1(),
new Project_Twig_Extension2(),
];
}
public function getFixturesDir()
{
return __DIR__.'/Fixtures/';
}
}
Fixtures examples can be found within the Twig repository
`tests/Twig/Fixtures`_ directory.
Node Tests
~~~~~~~~~~
Testing the node visitors can be complex, so extend your test cases from
``\Twig\Test\NodeTestCase``. Examples can be found in the Twig repository
`tests/Twig/Node`_ directory.
.. _`rot13`: https://secure.php.net/manual/en/function.str-rot13.php
.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/2.x/tests/Fixtures
.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/2.x/tests/Node
php-twig-2.12.5/doc/api.rst 0000664 0000000 0000000 00000047672 13624573447 0015447 0 ustar 00root root 0000000 0000000 Twig for Developers
===================
This chapter describes the API to Twig and not the template language. It will
be most useful as reference to those implementing the template interface to
the application and not those who are creating Twig templates.
Basics
------
Twig uses a central object called the **environment** (of class
``\Twig\Environment``). Instances of this class are used to store the
configuration and extensions, and are used to load templates.
Most applications create one ``\Twig\Environment`` object on application
initialization and use that to load templates. In some cases, it might be useful
to have multiple environments side by side, with different configurations.
The typical way to configure Twig to load templates for an application looks
roughly like this::
require_once '/path/to/vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
$twig = new \Twig\Environment($loader, [
'cache' => '/path/to/compilation_cache',
]);
This creates a template environment with a default configuration and a loader
that looks up templates in the ``/path/to/templates/`` directory. Different
loaders are available and you can also write your own if you want to load
templates from a database or other resources.
.. note::
Notice that the second argument of the environment is an array of options.
The ``cache`` option is a compilation cache directory, where Twig caches
the compiled templates to avoid the parsing phase for sub-sequent
requests. It is very different from the cache you might want to add for
the evaluated templates. For such a need, you can use any available PHP
cache library.
Rendering Templates
-------------------
To load a template from a Twig environment, call the ``load()`` method which
returns a ``\Twig\TemplateWrapper`` instance::
$template = $twig->load('index.html');
To render the template with some variables, call the ``render()`` method::
echo $template->render(['the' => 'variables', 'go' => 'here']);
.. note::
The ``display()`` method is a shortcut to output the rendered template.
You can also load and render the template in one fell swoop::
echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']);
If a template defines blocks, they can be rendered individually via the
``renderBlock()`` call::
echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);
.. _environment_options:
Environment Options
-------------------
When creating a new ``\Twig\Environment`` instance, you can pass an array of
options as the constructor second argument::
$twig = new \Twig\Environment($loader, ['debug' => true]);
The following options are available:
* ``debug`` *boolean*
When set to ``true``, the generated templates have a
``__toString()`` method that you can use to display the generated nodes
(default to ``false``).
* ``charset`` *string* (defaults to ``utf-8``)
The charset used by the templates.
* ``base_template_class`` *string* (defaults to ``\Twig\Template``)
The base template class to use for generated
templates.
* ``cache`` *string* or ``false``
An absolute path where to store the compiled templates, or
``false`` to disable caching (which is the default).
* ``auto_reload`` *boolean*
When developing with Twig, it's useful to recompile the
template whenever the source code changes. If you don't provide a value for
the ``auto_reload`` option, it will be determined automatically based on the
``debug`` value.
* ``strict_variables`` *boolean*
If set to ``false``, Twig will silently ignore invalid
variables (variables and or attributes/methods that do not exist) and
replace them with a ``null`` value. When set to ``true``, Twig throws an
exception instead (default to ``false``).
* ``autoescape`` *string*
Sets the default auto-escaping strategy (``name``, ``html``, ``js``, ``css``,
``url``, ``html_attr``, or a PHP callback that takes the template "filename"
and returns the escaping strategy to use -- the callback cannot be a function
name to avoid collision with built-in escaping strategies); set it to
``false`` to disable auto-escaping. The ``name`` escaping strategy determines
the escaping strategy to use for a template based on the template filename
extension (this strategy does not incur any overhead at runtime as
auto-escaping is done at compilation time.)
* ``optimizations`` *integer*
A flag that indicates which optimizations to apply
(default to ``-1`` -- all optimizations are enabled; set it to ``0`` to
disable).
Loaders
-------
Loaders are responsible for loading templates from a resource such as the file
system.
Compilation Cache
~~~~~~~~~~~~~~~~~
All template loaders can cache the compiled templates on the filesystem for
future reuse. It speeds up Twig a lot as templates are only compiled once; and
the performance boost is even larger if you use a PHP accelerator such as
OPCache. See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment``
above for more information.
Built-in Loaders
~~~~~~~~~~~~~~~~
Here is a list of the built-in loaders:
``\Twig\Loader\FilesystemLoader``
.................................
``\Twig\Loader\FilesystemLoader`` loads templates from the file system. This loader
can find templates in folders on the file system and is the preferred way to
load them::
$loader = new \Twig\Loader\FilesystemLoader($templateDir);
It can also look for templates in an array of directories::
$loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]);
With such a configuration, Twig will first look for templates in
``$templateDir1`` and if they do not exist, it will fallback to look for them
in the ``$templateDir2``.
You can add or prepend paths via the ``addPath()`` and ``prependPath()``
methods::
$loader->addPath($templateDir3);
$loader->prependPath($templateDir4);
The filesystem loader also supports namespaced templates. This allows to group
your templates under different namespaces which have their own template paths.
When using the ``setPaths()``, ``addPath()``, and ``prependPath()`` methods,
specify the namespace as the second argument (when not specified, these
methods act on the "main" namespace)::
$loader->addPath($templateDir, 'admin');
Namespaced templates can be accessed via the special
``@namespace_name/template_path`` notation::
$twig->render('@admin/index.html', []);
``\Twig\Loader\FilesystemLoader`` support absolute and relative paths. Using relative
paths is preferred as it makes the cache keys independent of the project root
directory (for instance, it allows warming the cache from a build server where
the directory might be different from the one used on production servers)::
$loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..');
.. note::
When not passing the root path as a second argument, Twig uses ``getcwd()``
for relative paths.
``\Twig\Loader\ArrayLoader``
............................
``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It is passed an
array of strings bound to template names::
$loader = new \Twig\Loader\ArrayLoader([
'index.html' => 'Hello {{ name }}!',
]);
$twig = new \Twig\Environment($loader);
echo $twig->render('index.html', ['name' => 'Fabien']);
This loader is very useful for unit testing. It can also be used for small
projects where storing all templates in a single PHP file might make sense.
.. tip::
When using the ``Array`` loader with a cache mechanism, you should know that
a new cache key is generated each time a template content "changes" (the
cache key being the source code of the template). If you don't want to see
your cache grows out of control, you need to take care of clearing the old
cache file by yourself.
``\Twig\Loader\ChainLoader``
............................
``\Twig\Loader\ChainLoader`` delegates the loading of templates to other loaders::
$loader1 = new \Twig\Loader\ArrayLoader([
'base.html' => '{% block content %}{% endblock %}',
]);
$loader2 = new \Twig\Loader\ArrayLoader([
'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
'base.html' => 'Will never be loaded',
]);
$loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]);
$twig = new \Twig\Environment($loader);
When looking for a template, Twig tries each loader in turn and returns as soon
as the template is found. When rendering the ``index.html`` template from the
above example, Twig will load it with ``$loader2`` but the ``base.html``
template will be loaded from ``$loader1``.
.. note::
You can also add loaders via the ``addLoader()`` method.
Create your own Loader
~~~~~~~~~~~~~~~~~~~~~~
All loaders implement the ``\Twig\Loader\LoaderInterface``::
interface \Twig\Loader\LoaderInterface
{
/**
* Returns the source context for a given template logical name.
*
* @param string $name The template logical name
*
* @return \Twig\Source
*
* @throws \Twig\Error\LoaderError When $name is not found
*/
public function getSourceContext($name);
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param string $name The name of the template to load
*
* @return string The cache key
*
* @throws \Twig\Error\LoaderError When $name is not found
*/
public function getCacheKey($name);
/**
* Returns true if the template is still fresh.
*
* @param string $name The template name
* @param timestamp $time The last modification time of the cached template
*
* @return bool true if the template is fresh, false otherwise
*
* @throws \Twig\Error\LoaderError When $name is not found
*/
public function isFresh($name, $time);
/**
* Check if we have the source code of a template, given its name.
*
* @param string $name The name of the template to check if we can load
*
* @return bool If the template source code is handled by this loader or not
*/
public function exists($name);
}
The ``isFresh()`` method must return ``true`` if the current cached template
is still fresh, given the last modification time, or ``false`` otherwise.
The ``getSourceContext()`` method must return an instance of ``\Twig\Source``.
Using Extensions
----------------
Twig extensions are packages that add new features to Twig. Register an
extension via the ``addExtension()`` method::
$twig->addExtension(new \Twig\Extension\SandboxExtension());
Twig comes bundled with the following extensions:
* *Twig\Extension\CoreExtension*: Defines all the core features of Twig.
* *Twig\Extension\DebugExtension*: Defines the ``dump`` function to help debug
template variables.
* *Twig\Extension\EscaperExtension*: Adds automatic output-escaping and the
possibility to escape/unescape blocks of code.
* *Twig\Extension\SandboxExtension*: Adds a sandbox mode to the default Twig
environment, making it safe to evaluate untrusted code.
* *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler.
* *Twig\Extension\OptimizerExtension*: Optimizes the node tree before
compilation.
* *Twig\Extension\StringLoaderExtension*: Defined the ``template_from_string``
function to allow loading templates from string in a template.
The Core, Escaper, and Optimizer extensions are registered by default.
Built-in Extensions
-------------------
This section describes the features added by the built-in extensions.
.. tip::
Read the chapter about :doc:`extending Twig ` to learn how to
create your own extensions.
Core Extension
~~~~~~~~~~~~~~
The ``core`` extension defines all the core features of Twig:
* :doc:`Tags `;
* :doc:`Filters `;
* :doc:`Functions `;
* :doc:`Tests `.
Escaper Extension
~~~~~~~~~~~~~~~~~
The ``escaper`` extension adds automatic output escaping to Twig. It defines a
tag, ``autoescape``, and a filter, ``raw``.
When creating the escaper extension, you can switch on or off the global
output escaping strategy::
$escaper = new \Twig\Extension\EscaperExtension('html');
$twig->addExtension($escaper);
If set to ``html``, all variables in templates are escaped (using the ``html``
escaping strategy), except those using the ``raw`` filter:
.. code-block:: twig
{{ article.to_html|raw }}
You can also change the escaping mode locally by using the ``autoescape`` tag:
.. code-block:: twig
{% autoescape 'html' %}
{{ var }}
{{ var|raw }} {# var won't be escaped #}
{{ var|escape }} {# var won't be double-escaped #}
{% endautoescape %}
.. warning::
The ``autoescape`` tag has no effect on included files.
The escaping rules are implemented as follows:
* Literals (integers, booleans, arrays, ...) used in the template directly as
variables or filter arguments are never automatically escaped:
.. code-block:: twig
{{ "Twig " }} {# won't be escaped #}
{% set text = "Twig " %}
{{ text }} {# will be escaped #}
* Expressions which the result is a literal or a variable marked safe
are never automatically escaped:
.. code-block:: twig
{{ foo ? "Twig " : " Twig" }} {# won't be escaped #}
{% set text = "Twig " %}
{{ true ? text : " Twig" }} {# will be escaped #}
{{ false ? text : " Twig" }} {# won't be escaped #}
{% set text = "Twig " %}
{{ foo ? text|raw : " Twig" }} {# won't be escaped #}
* Objects with a ``__toString`` method are converted to strings and
escaped. You can mark some classes and/or interfaces as being safe for some
strategies via ``EscaperExtension::addSafeClass()``:
.. code-block:: twig
// mark object of class Foo as safe for the HTML strategy
$escaper->addSafeClass('Foo', ['html']);
// mark object of interface Foo as safe for the HTML strategy
$escaper->addSafeClass('FooInterface', ['html']);
// mark object of class Foo as safe for the HTML and JS strategies
$escaper->addSafeClass('Foo', ['html', 'js']);
// mark object of class Foo as safe for all strategies
$escaper->addSafeClass('Foo', ['all']);
* Escaping is applied before printing, after any other filter is applied:
.. code-block:: twig
{{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
* The `raw` filter should only be used at the end of the filter chain:
.. code-block:: twig
{{ var|raw|upper }} {# will be escaped #}
{{ var|upper|raw }} {# won't be escaped #}
* Automatic escaping is not applied if the last filter in the chain is marked
safe for the current context (e.g. ``html`` or ``js``). ``escape`` and
``escape('html')`` are marked safe for HTML, ``escape('js')`` is marked
safe for JavaScript, ``raw`` is marked safe for everything.
.. code-block:: twig
{% autoescape 'js' %}
{{ var|escape('html') }} {# will be escaped for HTML and JavaScript #}
{{ var }} {# will be escaped for JavaScript #}
{{ var|escape('js') }} {# won't be double-escaped #}
{% endautoescape %}
.. note::
Note that autoescaping has some limitations as escaping is applied on
expressions after evaluation. For instance, when working with
concatenation, ``{{ foo|raw ~ bar }}`` won't give the expected result as
escaping is applied on the result of the concatenation, not on the
individual variables (so, the ``raw`` filter won't have any effect here).
Sandbox Extension
~~~~~~~~~~~~~~~~~
The ``sandbox`` extension can be used to evaluate untrusted code. Access to
unsafe attributes and methods is prohibited. The sandbox security is managed
by a policy instance. By default, Twig comes with one policy class:
``\Twig\Sandbox\SecurityPolicy``. This class allows you to white-list some
tags, filters, properties, and methods::
$tags = ['if'];
$filters = ['upper'];
$methods = [
'Article' => ['getTitle', 'getBody'],
];
$properties = [
'Article' => ['title', 'body'],
];
$functions = ['range'];
$policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions);
With the previous configuration, the security policy will only allow usage of
the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be
able to call the ``getTitle()`` and ``getBody()`` methods on ``Article``
objects, and the ``title`` and ``body`` public properties. Everything else
won't be allowed and will generate a ``\Twig\Sandbox\SecurityError`` exception.
The policy object is the first argument of the sandbox constructor::
$sandbox = new \Twig\Extension\SandboxExtension($policy);
$twig->addExtension($sandbox);
By default, the sandbox mode is disabled and should be enabled when including
untrusted template code by using the ``sandbox`` tag:
.. code-block:: twig
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
You can sandbox all templates by passing ``true`` as the second argument of
the extension constructor::
$sandbox = new \Twig\Extension\SandboxExtension($policy, true);
Profiler Extension
~~~~~~~~~~~~~~~~~~
The ``profiler`` extension enables a profiler for Twig templates; it should
only be used on your development machines as it adds some overhead::
$profile = new \Twig\Profiler\Profile();
$twig->addExtension(new \Twig\Extension\ProfilerExtension($profile));
$dumper = new \Twig\Profiler\Dumper\TextDumper();
echo $dumper->dump($profile);
A profile contains information about time and memory consumption for template,
block, and macro executions.
You can also dump the data in a `Blackfire.io `_
compatible format::
$dumper = new \Twig\Profiler\Dumper\BlackfireDumper();
file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
Upload the profile to visualize it (create a `free account
`_
first):
.. code-block:: sh
blackfire --slot=7 upload /path/to/profile.prof
Optimizer Extension
~~~~~~~~~~~~~~~~~~~
The ``optimizer`` extension optimizes the node tree before compilation::
$twig->addExtension(new \Twig\Extension\OptimizerExtension());
By default, all optimizations are turned on. You can select the ones you want
to enable by passing them to the constructor::
$optimizer = new \Twig\Extension\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR);
$twig->addExtension($optimizer);
Twig supports the following optimizations:
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations
(this is the default value).
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations.
This reduces the compilation time, but it can increase the execution time
and the consumed memory.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by
removing the ``loop`` variable creation whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw``
filter whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation
and access of variables in the compiled templates whenever possible.
Exceptions
----------
Twig can throw exceptions:
* ``\Twig\Error\Error``: The base exception for all errors.
* ``\Twig\Error\SyntaxError``: Thrown to tell the user that there is a problem with
the template syntax.
* ``\Twig\Error\RuntimeError``: Thrown when an error occurs at runtime (when a filter
does not exist for instance).
* ``\Twig\Error\LoaderError``: Thrown when an error occurs during template loading.
* ``\Twig\Sandbox\SecurityError``: Thrown when an unallowed tag, filter, or
method is called in a sandboxed template.
php-twig-2.12.5/doc/coding_standards.rst 0000664 0000000 0000000 00000004506 13624573447 0020171 0 ustar 00root root 0000000 0000000 Coding Standards
================
When writing Twig templates, we recommend you to follow these official coding
standards:
* Put one (and only one) space after the start of a delimiter (``{{``, ``{%``,
and ``{#``) and before the end of a delimiter (``}}``, ``%}``, and ``#}``):
.. code-block:: twig
{{ foo }}
{# comment #}
{% if foo %}{% endif %}
When using the whitespace control character, do not put any spaces between
it and the delimiter:
.. code-block:: twig
{{- foo -}}
{#- comment -#}
{%- if foo -%}{%- endif -%}
* Put one (and only one) space before and after the following operators:
comparison operators (``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``), math
operators (``+``, ``-``, ``/``, ``*``, ``%``, ``//``, ``**``), logic
operators (``not``, ``and``, ``or``), ``~``, ``is``, ``in``, and the ternary
operator (``?:``):
.. code-block:: twig
{{ 1 + 2 }}
{{ foo ~ bar }}
{{ true ? true : false }}
* Put one (and only one) space after the ``:`` sign in hashes and ``,`` in
arrays and hashes:
.. code-block:: twig
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
* Do not put any spaces after an opening parenthesis and before a closing
parenthesis in expressions:
.. code-block:: twig
{{ 1 + (2 * 3) }}
* Do not put any spaces before and after string delimiters:
.. code-block:: twig
{{ 'foo' }}
{{ "foo" }}
* Do not put any spaces before and after the following operators: ``|``,
``.``, ``..``, ``[]``:
.. code-block:: twig
{{ foo|upper|lower }}
{{ user.name }}
{{ user[name] }}
{% for i in 1..12 %}{% endfor %}
* Do not put any spaces before and after the parenthesis used for filter and
function calls:
.. code-block:: twig
{{ foo|default('foo') }}
{{ range(1..10) }}
* Do not put any spaces before and after the opening and the closing of arrays
and hashes:
.. code-block:: twig
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
* Use lower cased and underscored variable names:
.. code-block:: twig
{% set foo = 'foo' %}
{% set foo_bar = 'foo' %}
* Indent your code inside tags (use the same indentation as the one used for
the target language of the rendered template):
.. code-block:: twig
{% block foo %}
{% if true %}
true
{% endif %}
{% endblock %}
php-twig-2.12.5/doc/deprecated.rst 0000664 0000000 0000000 00000010116 13624573447 0016755 0 ustar 00root root 0000000 0000000 Deprecated Features
===================
This document lists deprecated features in Twig 2.x. Deprecated features are
kept for backward compatibility and removed in the next major release (a
feature that was deprecated in Twig 2.x is removed in Twig 3.0).
PSR-0
-----
* PSR-0 classes are deprecated in favor of namespaced ones since Twig 2.7.
Inheritance
-----------
* Defining a "block" definition in a non-capturing block in a child template is
deprecated since Twig 2.5.0. In Twig 3.0, it will throw a
``Twig\Error\SyntaxError`` exception. It does not work anyway, so most
projects won't need to do anything to upgrade.
Errors
------
* Passing a string as the ``$source`` argument on ``\Twig\Error\Error`` /
``Twig\Error\Error`` constructor is deprecated since Twig 2.6.1. Pass an
instance of ``Twig\Source`` instead.
Tags
----
* The ``spaceless`` tag is deprecated in Twig 2.7. Use the ``spaceless`` filter
instead or ``{% apply spaceless %}`` (the ``Twig\Node\SpacelessNode`` and
``Twig\TokenParser\SpacelessTokenParser`` classes are also deprecated).
* Using the ``spaceless`` tag at the root level of a child template is
deprecated in Twig 2.5.0. This does not work as one would expect it to work
anyway. In Twig 3.0, it will throw a ``Twig\Error\SyntaxError`` exception.
* The ``filter`` tag is deprecated in Twig 2.9. Use the ``apply`` tag instead
(the ``Twig\TokenParser\FilterTokenParser`` classes is also deprecated).
* Adding an ``if`` condition on a ``for`` tag is deprecated in Twig 2.10. Use a
``filter`` filter or an "if" condition inside the "for" body instead (if your condition
depends on a variable updated inside the loop)
Final Classes
-------------
The following classes are marked as ``@final`` in Twig 2 and will be final in
3.0:
* ``Twig\Node\ModuleNode``
* ``Twig\TwigFilter``
* ``Twig\TwigFunction``
* ``Twig\TwigTest``
* ``Twig\Profiler\Profile``
Parser
------
* As of Twig 2.7, the ``\Twig\Parser::isReservedMacroName()`` / ``Twig\Parser``
function is deprecated and will be removed in Twig 3.0. It always returns
``false`` anyway as Twig 2 does not have any reserved macro names.
Environment
-----------
* As of Twig 2.7, the ``base_template_class`` option on ``Twig\Environment`` is
deprecated and will be removed in Twig 3.0.
* As of Twig 2.7, the ``Twig\Environment::getBaseTemplateClass()`` and
``Twig\Environment::setBaseTemplateClass()`` methods are deprecated and will
be removed in Twig 3.0.
* As of Twig 2.7, the ``Twig\Environment::getTemplateClass()`` is marked as
being internal and should not be used.
* As of Twig 2.7, passing a ``Twig\Template`` instance to the
``Twig\Environment::load()`` and ``Twig\Environment::resolveTemplate()`` is
deprecated.
* Depending on the input, ``Twig\Environment::resolveTemplate()`` can return
a ``Twig\Template`` or a ``Twig\TemplateWrapper`` instance. In Twig 3.0, this
method will **always** return a ``Twig\TemplateWrapper`` instance. You should
only rely on the methods of this class if you want to be forward-compatible.
Interfaces
----------
* As of Twig 2.7, the empty ``Twig\Loader\ExistsLoaderInterface`` interface is
deprecated and will be removed in Twig 3.0.
* As of Twig 2.7, the ``Twig\Extension\InitRuntimeInterface`` interface is
deprecated and will be removed in Twig 3.0.
Extensions
----------
* As of Twig 2.11, the ``Twig\Extension\CoreExtension::setEscaper()`` and
``Twig\Extension\CoreExtension::getEscapers()`` are deprecated. Use the same
methods on ``Twig\Extension\EscaperExtension`` instead.
Miscellaneous
-------------
* As of Twig 2.7, the ``Twig_SimpleFilter``, ``Twig_SimpleFunction``, and
``Twig_SimpleTest`` empty classes are deprecated and will be removed in Twig
3.0. Use ``Twig\TwigFilter``, ``Twig\TwigFunction``, and ``Twig\TwigTest``
respectively.
* As of Twig 2.8.2, all usage of
``Twig\Loader\FilesystemLoader::findTemplate()`` check for a ``null`` return
value (same meaning as returning ``false``). If you are overidding
``Twig\Loader\FilesystemLoader::findTemplate()``, you must return ``null`` instead of ``false``
to be compatible with Twig 3.0.
php-twig-2.12.5/doc/filters/ 0000775 0000000 0000000 00000000000 13624573447 0015574 5 ustar 00root root 0000000 0000000 php-twig-2.12.5/doc/filters/abs.rst 0000664 0000000 0000000 00000000376 13624573447 0017101 0 ustar 00root root 0000000 0000000 ``abs``
=======
The ``abs`` filter returns the absolute value.
.. code-block:: twig
{# number = -5 #}
{{ number|abs }}
{# outputs 5 #}
.. note::
Internally, Twig uses the PHP `abs`_ function.
.. _`abs`: https://secure.php.net/abs
php-twig-2.12.5/doc/filters/batch.rst 0000664 0000000 0000000 00000002050 13624573447 0017404 0 ustar 00root root 0000000 0000000 ``batch``
=========
The ``batch`` filter "batches" items by returning a list of lists with the
given number of items. A second parameter can be provided and used to fill in
missing items:
.. code-block:: twig
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
{% for row in items|batch(3, 'No item') %}
{% for column in row %}
{{ column }}
{% endfor %}
{% endfor %}
The above example will be rendered as:
.. code-block:: twig
a
b
c
d
e
f
g
No item
No item
Arguments
---------
* ``size``: The size of the batch; fractional numbers will be rounded up
* ``fill``: Used to fill in missing items
* ``preserve_keys``: Whether to preserve keys or not
php-twig-2.12.5/doc/filters/capitalize.rst 0000664 0000000 0000000 00000000350 13624573447 0020451 0 ustar 00root root 0000000 0000000 ``capitalize``
==============
The ``capitalize`` filter capitalizes a value. The first character will be
uppercase, all others lowercase:
.. code-block:: twig
{{ 'my first car'|capitalize }}
{# outputs 'My first car' #}
php-twig-2.12.5/doc/filters/column.rst 0000664 0000000 0000000 00000001053 13624573447 0017622 0 ustar 00root root 0000000 0000000 ``column``
==========
.. versionadded:: 2.8
The ``column`` filter was added in Twig 2.8.
The ``column`` filter returns the values from a single column in the input
array.
.. code-block:: twig
{% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
{% set fruits = items|column('fruit') %}
{# fruits now contains ['apple', 'orange'] #}
.. note::
Internally, Twig uses the PHP `array_column`_ function.
Arguments
---------
* ``name``: The column name to extract
.. _`array_column`: https://secure.php.net/array_column
php-twig-2.12.5/doc/filters/convert_encoding.rst 0000664 0000000 0000000 00000000741 13624573447 0021656 0 ustar 00root root 0000000 0000000 ``convert_encoding``
====================
The ``convert_encoding`` filter converts a string from one encoding to
another. The first argument is the expected output charset and the second one
is the input charset:
.. code-block:: twig
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
.. note::
This filter relies on the `iconv`_ extension.
Arguments
---------
* ``to``: The output charset
* ``from``: The input charset
.. _`iconv`: https://secure.php.net/iconv
php-twig-2.12.5/doc/filters/country_name.rst 0000664 0000000 0000000 00000001650 13624573447 0021033 0 ustar 00root root 0000000 0000000 ``country_name``
================
.. versionadded:: 2.12
The ``country_name`` filter was added in Twig 2.12.
The ``country_name`` filter returns the country name given its ISO-3166
two-letter code:
.. code-block:: twig
{# France #}
{{ 'FR'|country_name }}
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# États-Unis #}
{{ 'US'|country_name('fr') }}
.. note::
The ``country_name`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
php-twig-2.12.5/doc/filters/currency_name.rst 0000664 0000000 0000000 00000001743 13624573447 0021165 0 ustar 00root root 0000000 0000000 ``currency_name``
=================
.. versionadded:: 2.12
The ``currency_name`` filter was added in Twig 2.12.
The ``currency_name`` filter returns the currency name given its three-letter
code:
.. code-block:: twig
{# Euro #}
{{ 'EUR'|currency_name }}
{# Japanese Yen #}
{{ 'JPY'|currency_name }}
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# yen japonais #}
{{ 'JPY'|currency_name('fr_FR') }}
.. note::
The ``currency_name`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
php-twig-2.12.5/doc/filters/currency_symbol.rst 0000664 0000000 0000000 00000001735 13624573447 0021553 0 ustar 00root root 0000000 0000000 ``currency_symbol``
===================
.. versionadded:: 2.12
The ``currency_symbol`` filter was added in Twig 2.12.
The ``currency_symbol`` filter returns the currency symbol given its three-letter
code:
.. code-block:: twig
{# € #}
{{ 'EUR'|currency_symbol }}
{# ¥ #}
{{ 'JPY'|currency_symbol }}
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# ¥ #}
{{ 'JPY'|currency_symbol('fr') }}
.. note::
The ``currency_symbol`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
php-twig-2.12.5/doc/filters/data_uri.rst 0000664 0000000 0000000 00000002470 13624573447 0020121 0 ustar 00root root 0000000 0000000 ``data_uri``
============
.. versionadded:: 2.12
The ``data_uri`` filter was added in Twig 2.12.
The ``data_uri`` filter generates a URL using the data scheme as defined in RFC
2397:
.. code-block:: twig
{{ image_data|data_uri }}
{{ source('path_to_image')|data_uri }}
{# force the mime type, disable the guessing of the mime type #}
{{ image_data|data_uri(mime="image/svg") }}
{# also works with plain text #}
{{ 'foobar'|data_uri(mime="text/html") }}
{# add some extra parameters #}
{{ 'foobar'|data_uri(mime="text/html", parameters={charset: "ascii"}) }}
.. note::
The ``data_uri`` filter is part of the ``HtmlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/html-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Html\HtmlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new HtmlExtension());
.. note::
The filter does not perform any length validation on purpose (limits depends
on the usage context), validation should be done before calling this filter.
Arguments
---------
* ``mime``: The mime type
* ``parameters``: An array of parameters
php-twig-2.12.5/doc/filters/date.rst 0000664 0000000 0000000 00000005104 13624573447 0017243 0 ustar 00root root 0000000 0000000 ``date``
========
The ``date`` filter formats a date to a given format:
.. code-block:: twig
{{ post.published_at|date("m/d/Y") }}
The format specifier is the same as supported by `date`_,
except when the filtered data is of type `DateInterval`_, when the format must conform to
`DateInterval::format`_ instead.
The ``date`` filter accepts strings (it must be in a format supported by the
`strtotime`_ function), `DateTime`_ instances, or `DateInterval`_ instances. For
instance, to display the current date, filter the word "now":
.. code-block:: twig
{{ "now"|date("m/d/Y") }}
To escape words and characters in the date format use ``\\`` in front of each
character:
.. code-block:: twig
{{ post.published_at|date("F jS \\a\\t g:ia") }}
If the value passed to the ``date`` filter is ``null``, it will return the
current date by default. If an empty string is desired instead of the current
date, use a ternary operator:
.. code-block:: twig
{{ post.published_at is empty ? "" : post.published_at|date("m/d/Y") }}
If no format is provided, Twig will use the default one: ``F j, Y H:i``. This
default can be changed by calling the ``setDateFormat()`` method on the
``core`` extension instance. The first argument is the default format for
dates and the second one is the default format for date intervals:
.. code-block:: php
$twig = new \Twig\Environment($loader);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('d/m/Y', '%d days');
Timezone
--------
By default, the date is displayed by applying the default timezone (the one
specified in php.ini or declared in Twig -- see below), but you can override
it by explicitly specifying a timezone:
.. code-block:: twig
{{ post.published_at|date("m/d/Y", "Europe/Paris") }}
If the date is already a DateTime object, and if you want to keep its current
timezone, pass ``false`` as the timezone value:
.. code-block:: twig
{{ post.published_at|date("m/d/Y", false) }}
The default timezone can also be set globally by calling ``setTimezone()``:
.. code-block:: php
$twig = new \Twig\Environment($loader);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Europe/Paris');
Arguments
---------
* ``format``: The date format
* ``timezone``: The date timezone
.. _`strtotime`: https://secure.php.net/strtotime
.. _`DateTime`: https://secure.php.net/DateTime
.. _`DateInterval`: https://secure.php.net/DateInterval
.. _`date`: https://secure.php.net/date
.. _`DateInterval::format`: https://secure.php.net/DateInterval.format
php-twig-2.12.5/doc/filters/date_modify.rst 0000664 0000000 0000000 00000001043 13624573447 0020610 0 ustar 00root root 0000000 0000000 ``date_modify``
===============
The ``date_modify`` filter modifies a date with a given modifier string:
.. code-block:: twig
{{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}
The ``date_modify`` filter accepts strings (it must be in a format supported
by the `strtotime`_ function) or `DateTime`_ instances. You can combine
it with the :doc:`date` filter for formatting.
Arguments
---------
* ``modifier``: The modifier
.. _`strtotime`: https://secure.php.net/strtotime
.. _`DateTime`: https://secure.php.net/DateTime
php-twig-2.12.5/doc/filters/default.rst 0000664 0000000 0000000 00000001530 13624573447 0017751 0 ustar 00root root 0000000 0000000 ``default``
===========
The ``default`` filter returns the passed default value if the value is
undefined or empty, otherwise the value of the variable:
.. code-block:: twig
{{ var|default('var is not defined') }}
{{ var.foo|default('foo item on var is not defined') }}
{{ var['foo']|default('foo item on var is not defined') }}
{{ ''|default('passed var is empty') }}
When using the ``default`` filter on an expression that uses variables in some
method calls, be sure to use the ``default`` filter whenever a variable can be
undefined:
.. code-block:: twig
{{ var.method(foo|default('foo'))|default('foo') }}
.. note::
Read the documentation for the :doc:`defined<../tests/defined>` and
:doc:`empty<../tests/empty>` tests to learn more about their semantics.
Arguments
---------
* ``default``: The default value
php-twig-2.12.5/doc/filters/escape.rst 0000664 0000000 0000000 00000006731 13624573447 0017575 0 ustar 00root root 0000000 0000000 ``escape``
==========
The ``escape`` filter escapes a string using strategies that depend on the
context.
By default, it uses the HTML escaping strategy:
.. code-block:: html+twig
{{ user.username|escape }}
For convenience, the ``e`` filter is defined as an alias:
.. code-block:: html+twig
{{ user.username|e }}
The ``escape`` filter can also be used in other contexts than HTML thanks to
an optional argument which defines the escaping strategy to use:
.. code-block:: twig
{{ user.username|e }}
{# is equivalent to #}
{{ user.username|e('html') }}
And here is how to escape variables included in JavaScript code:
.. code-block:: twig
{{ user.username|escape('js') }}
{{ user.username|e('js') }}
The ``escape`` filter supports the following escaping strategies for HTML
documents:
* ``html``: escapes a string for the **HTML body** context.
* ``js``: escapes a string for the **JavaScript** context.
* ``css``: escapes a string for the **CSS** context. CSS escaping can be
applied to any string being inserted into CSS and escapes everything except
alphanumerics.
* ``url``: escapes a string for the **URI or parameter** contexts. This should
not be used to escape an entire URI; only a subcomponent being inserted.
* ``html_attr``: escapes a string for the **HTML attribute** context.
Note that doing contextual escaping in HTML documents is hard and choosing the
right escaping strategy depends on a lot of factors. Please, read related
documentation like `the OWASP prevention cheat sheet
`_
to learn more about this topic.
.. note::
Internally, ``escape`` uses the PHP native `htmlspecialchars`_ function
for the HTML escaping strategy.
.. caution::
When using automatic escaping, Twig tries to not double-escape a variable
when the automatic escaping strategy is the same as the one applied by the
escape filter; but that does not work when using a variable as the
escaping strategy:
.. code-block:: twig
{% set strategy = 'html' %}
{% autoescape 'html' %}
{{ var|escape('html') }} {# won't be double-escaped #}
{{ var|escape(strategy) }} {# will be double-escaped #}
{% endautoescape %}
When using a variable as the escaping strategy, you should disable
automatic escaping:
.. code-block:: twig
{% set strategy = 'html' %}
{% autoescape 'html' %}
{{ var|escape(strategy)|raw }} {# won't be double-escaped #}
{% endautoescape %}
Custom Escapers
---------------
You can define custom escapers by calling the ``setEscaper()`` method on the
``core`` extension instance. The first argument is the escaper name (to be
used in the ``escape`` call) and the second one must be a valid PHP callable:
.. code-block:: php
$twig = new \Twig\Environment($loader);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setEscaper('csv', 'csv_escaper');
When called by Twig, the callable receives the Twig environment instance, the
string to escape, and the charset.
.. note::
Built-in escapers cannot be overridden mainly because they should be
considered as the final implementation and also for better performance.
Arguments
---------
* ``strategy``: The escaping strategy
* ``charset``: The string charset
.. _`htmlspecialchars`: https://secure.php.net/htmlspecialchars
php-twig-2.12.5/doc/filters/filter.rst 0000664 0000000 0000000 00000002367 13624573447 0017623 0 ustar 00root root 0000000 0000000 ``filter``
==========
.. versionadded:: 1.41
The ``filter`` filter was added in Twig 1.41 and 2.10.
The ``filter`` filter filters elements of a sequence or a mapping using an arrow
function. The arrow function receives the value of the sequence or mapping:
.. code-block:: twig
{% set sizes = [34, 36, 38, 40, 42] %}
{{ sizes|filter(v => v > 38)|join(', ') }}
{# output 40, 42 #}
Combined with the ``for`` tag, it allows to filter the items to iterate over:
.. code-block:: twig
{% for v in sizes|filter(v => v > 38) -%}
{{ v }}
{% endfor %}
{# output 40 42 #}
It also works with mappings:
.. code-block:: twig
{% set sizes = {
xs: 34,
s: 36,
m: 38,
l: 40,
xl: 42,
} %}
{% for k, v in sizes|filter(v => v > 38) -%}
{{ k }} = {{ v }}
{% endfor %}
{# output l = 40 xl = 42 #}
The arrow function also receives the key as a second argument:
.. code-block:: twig
{% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%}
{{ k }} = {{ v }}
{% endfor %}
{# output l = 40 #}
Note that the arrow function has access to the current context.
Arguments
---------
* ``array``: The sequence or mapping
* ``arrow``: The arrow function
php-twig-2.12.5/doc/filters/first.rst 0000664 0000000 0000000 00000000702 13624573447 0017454 0 ustar 00root root 0000000 0000000 ``first``
=========
The ``first`` filter returns the first "element" of a sequence, a mapping, or
a string:
.. code-block:: twig
{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}
{{ '1234'|first }}
{# outputs 1 #}
.. note::
It also works with objects implementing the `Traversable`_ interface.
.. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php
php-twig-2.12.5/doc/filters/format.rst 0000664 0000000 0000000 00000000613 13624573447 0017616 0 ustar 00root root 0000000 0000000 ``format``
==========
The ``format`` filter formats a given string by replacing the placeholders
(placeholders follows the `sprintf`_ notation):
.. code-block:: twig
{{ "I like %s and %s."|format(foo, "bar") }}
{# outputs I like foo and bar
if the foo parameter equals to the foo string. #}
.. _`sprintf`: https://secure.php.net/sprintf
.. seealso:: :doc:`replace`
php-twig-2.12.5/doc/filters/format_currency.rst 0000664 0000000 0000000 00000003403 13624573447 0021530 0 ustar 00root root 0000000 0000000 ``format_currency``
===================
.. versionadded:: 2.12
The ``format_currency`` filter was added in Twig 2.12.
The ``format_currency`` filter formats a number as a currency:
.. code-block:: twig
{# €1,000,000.00 #}
{{ '1000000'|format_currency('EUR') }}
You can pass attributes to tweak the output:
.. code-block:: twig
{# €12.34 #}
{{ '12.345'|format_currency('EUR', {rounding_mode: 'floor'}) }}
{# €1,000,000.0000 #}
{{ '1000000'|format_currency('EUR', {fraction_digit: 4}) }}
The list of supported options:
* ``grouping_used``;
* ``decimal_always_shown``;
* ``max_integer_digit``;
* ``min_integer_digit``;
* ``integer_digit``;
* ``max_fraction_digit``;
* ``min_fraction_digit``;
* ``fraction_digit``;
* ``multiplier``;
* ``grouping_size``;
* ``rounding_mode``;
* ``rounding_increment``;
* ``format_width``;
* ``padding_position``;
* ``secondary_grouping_size``;
* ``significant_digits_used``;
* ``min_significant_digits_used``;
* ``max_significant_digits_used``;
* ``lenient_parse``.
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# 1.000.000,00 € #}
{{ '1000000'|format_currency('EUR', locale='de') }}
.. note::
The ``format_currency`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``currency``: The currency
* ``attrs``: A map of attributes
* ``locale``: The locale
php-twig-2.12.5/doc/filters/format_date.rst 0000664 0000000 0000000 00000001465 13624573447 0020621 0 ustar 00root root 0000000 0000000 ``format_date``
===============
.. versionadded:: 2.12
The ``format_date`` filter was added in Twig 2.12.
The ``format_date`` filter formats a date. It behaves in the exact same way as
the ``format_datetime`` filter, but without the time.
.. note::
The ``format_date`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
* ``dateFormat``: The date format
* ``pattern``: A date time pattern
php-twig-2.12.5/doc/filters/format_datetime.rst 0000664 0000000 0000000 00000003713 13624573447 0021476 0 ustar 00root root 0000000 0000000 ``format_datetime``
===================
.. versionadded:: 2.12
The ``format_datetime`` filter was added in Twig 2.12.
The ``format_datetime`` filter formats a date time:
public function formatDateTime(Environment $env, $date, ?string $dateFormat = 'medium', ?string $timeFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string
.. code-block:: twig
{# Aug 7, 2019, 11:39:12 PM #}
{{ '2019-08-07 23:39:12'|format_datetime() }}
You can tweak the output for the date part and the time part:
.. code-block:: twig
{# 23:39 #}
{{ '2019-08-07 23:39:12'|format_datetime('none', 'short', locale='fr') }}
{# 07/08/2019 #}
{{ '2019-08-07 23:39:12'|format_datetime('short', 'none', locale='fr') }}
{# mercredi 7 août 2019 23:39:12 UTC #}
{{ '2019-08-07 23:39:12'|format_datetime('full', 'full', locale='fr') }}
Supported values are: ``none``, ``short``, ``medium``, ``long``, and ``full``.
For greater flexiblity, you can even define your own pattern:
.. code-block:: twig
{# 11 oclock PM, GMT #}
{{ '2019-08-07 23:39:12'|format_datetime(pattern="hh 'oclock' a, zzzz") }}
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# 7 août 2019 23:39:12 #}
{{ '2019-08-07 23:39:12'|format_datetime(locale='fr') }}
.. note::
The ``format_datetime`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
* ``dateFormat``: The date format
* ``timeFormat``: The time format
* ``pattern``: A date time pattern
php-twig-2.12.5/doc/filters/format_number.rst 0000664 0000000 0000000 00000005145 13624573447 0021173 0 ustar 00root root 0000000 0000000 ``format_number``
=================
.. versionadded:: 2.12
The ``format_number`` filter was added in Twig 2.12.
The ``format_number`` filter formats a number:
.. code-block:: twig
{{ '12.345'|format_number }}
You can pass attributes to tweak the output:
.. code-block:: twig
{# 12.34 #}
{{ '12.345'|format_number({rounding_mode: 'floor'}) }}
{# 1000000.0000 #}
{{ '1000000'|format_number({fraction_digit: 4}) }}
The list of supported options:
* ``grouping_used``;
* ``decimal_always_shown``;
* ``max_integer_digit``;
* ``min_integer_digit``;
* ``integer_digit``;
* ``max_fraction_digit``;
* ``min_fraction_digit``;
* ``fraction_digit``;
* ``multiplier``;
* ``grouping_size``;
* ``rounding_mode``;
* ``rounding_increment``;
* ``format_width``;
* ``padding_position``;
* ``secondary_grouping_size``;
* ``significant_digits_used``;
* ``min_significant_digits_used``;
* ``max_significant_digits_used``;
* ``lenient_parse``.
Besides plain numbers, the filter can also format numbers in various styles:
.. code-block:: twig
{# 1,234% #}
{{ '12.345'|format_number(style='percent') }}
{# twelve point three four five #}
{{ '12.345'|format_number(style='spellout') }}
{# 12 sec. #}
{{ '12'|format_duration_number }}
The list of supported styles:
* ``decimal``;
* ``currency``;
* ``percent``;
* ``scientific``;
* ``spellout``;
* ``ordinal``;
* ``duration``.
As a shortcut, you can use the ``format_*_number`` filters by replacing `*` with
a style:
.. code-block:: twig
{# 1,234% #}
{{ '12.345'|format_percent_number }}
{# twelve point three four five #}
{{ '12.345'|format_spellout_number }}
You can pass attributes to tweak the output:
.. code-block:: twig
{# €12.34 #}
{{ '12.345'|format_number('EUR', {rounding_mode: 'floor'}) }}
{# €1,000,000.0000 #}
{{ '1000000'|format_number('EUR', {fraction_digit: 4}) }}
By default, the filter uses the current locale. You can pass it explicitly:
.. code-block:: twig
{# 12,345 #}
{{ '12.345'|format_number(locale='fr') }}
.. note::
The ``format_number`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
* ``attrs``: A map of attributes
* ``style``: The style of the number output
php-twig-2.12.5/doc/filters/format_time.rst 0000664 0000000 0000000 00000001465 13624573447 0020642 0 ustar 00root root 0000000 0000000 ``format_time``
===============
.. versionadded:: 2.12
The ``format_time`` filter was added in Twig 2.12.
The ``format_time`` filter formats a time. It behaves in the exact same way as
the ``format_datetime`` filter, but without the date.
.. note::
The ``format_time`` filter is part of the ``IntlExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/intl-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Intl\IntlExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());
Arguments
---------
* ``locale``: The locale
* ``timeFormat``: The time format
* ``pattern``: A date time pattern
php-twig-2.12.5/doc/filters/html_to_markdown.rst 0000664 0000000 0000000 00000003427 13624573447 0021704 0 ustar 00root root 0000000 0000000 ``html_to_markdown``
====================
.. versionadded:: 2.12
The ``html_to_markdown`` filter was added in Twig 2.12.
The ``html_to_markdown`` filter converts a block of HTML to Markdown:
.. code-block:: twig
{% apply html_to_markdown %}
Hello!
{% endapply %}
You can also add some options by passing them as an argument to the filter:
.. code-block:: twig
{% apply html_to_markdown({hard_break: false}) %}
Hello!
{% endapply %}
.. note::
The options are the ones provided by the ``league/html-to-markdown`` package.
You can also use the filter on an included file:
.. code-block:: twig
{{ include('some_template.html.twig')|html_to_markdown }}
.. note::
The ``html_to_markdown`` filter is part of the ``MarkdownExtension`` which
is not installed by default. Install it first:
.. code-block:: bash
$ composer req twig/markdown-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Markdown\MarkdownMarkdownExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new MarkdownExtension());
If you are not using Symfony, you must also register the extension runtime::
use Twig\Extra\Markdown\DefaultMarkdown;
use Twig\Extra\Markdown\MarkdownRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
public function load($class) {
if (MarkdownRuntime::class === $class) {
return new MarkdownRuntime(new DefaultMarkdown());
}
}
});
php-twig-2.12.5/doc/filters/index.rst 0000664 0000000 0000000 00000001353 13624573447 0017437 0 ustar 00root root 0000000 0000000 Filters
=======
.. toctree::
:maxdepth: 1
abs
batch
capitalize
column
convert_encoding
country_name
currency_name
currency_symbol
data_uri
date
date_modify
default
escape
filter
first
format
format_currency
format_date
format_datetime
format_number
format_time
html_to_markdown
inline_css
inky_to_html
join
json_encode
keys
language_name
last
length
locale_name
lower
map
markdown_to_html
merge
nl2br
number_format
raw
reduce
replace
reverse
round
slice
sort
spaceless
split
striptags
timezone_name
title
trim
u
upper
url_encode
php-twig-2.12.5/doc/filters/inky_to_html.rst 0000664 0000000 0000000 00000001733 13624573447 0021032 0 ustar 00root root 0000000 0000000 ``inky_to_html``
================
.. versionadded:: 2.12
The ``inky_to_html`` filter was added in Twig 2.12.
The ``inky_to_html`` filter processes an `inky email template
`_:
.. code-block:: twig
{% apply inky_to_html %}
{% endapply %}
You can also use the filter on an included file:
.. code-block:: twig
{{ include('some_template.inky.twig')|inky_to_html }}
.. note::
The ``inky_to_html`` filter is part of the ``InkyExtension`` which is not
installed by default. Install it first:
.. code-block:: bash
$ composer req twig/inky-extra
Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension
explictly on the Twig environment::
use Twig\Extra\Inky\InkyExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new InkyExtension());
php-twig-2.12.5/doc/filters/inline_css.rst 0000664 0000000 0000000 00000003167 13624573447 0020463 0 ustar 00root root 0000000 0000000 ``inline_css``
==============
.. versionadded:: 2.12
The ``inline_css`` filter was added in Twig 2.12.
The ``inline_css`` filter inline CSS styles in HTML documents:
.. code-block:: twig
{% apply inline_css %}
Hello CSS!
{% endapply %}
You can also add some stylesheets by passing them as arguments to the filter:
.. code-block:: twig
{% apply inline_css(source("some_styles.css"), source("another.css")) %}
Hello CSS!
{% endapply %}
Styles loaded via the filter override the styles defined in the ``
{% endblock %}
{% block content %}
Index
Welcome on my awesome homepage.
{% endblock %}
The ``extends`` tag is the key here. It tells the template engine that this
template "extends" another template. When the template system evaluates this
template, first it locates the parent. The extends tag should be the first tag
in the template.
Note that since the child template doesn't define the ``footer`` block, the
value from the parent template is used instead.
You can't define multiple ``block`` tags with the same name in the same
template. This limitation exists because a block tag works in "both"
directions. That is, a block tag doesn't just provide a hole to fill - it also
defines the content that fills the hole in the *parent*. If there were two
similarly-named ``block`` tags in a template, that template's parent wouldn't
know which one of the blocks' content to use.
If you want to print a block multiple times you can however use the
``block`` function:
.. code-block:: twig
{% block title %}{% endblock %}
{{ block('title') }}
{% block body %}{% endblock %}
Parent Blocks
-------------
It's possible to render the contents of the parent block by using the
:doc:`parent<../functions/parent>` function. This gives back the results of
the parent block:
.. code-block:: twig
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
Named Block End-Tags
--------------------
Twig allows you to put the name of the block after the end tag for better
readability (the name after the ``endblock`` word must match the block name):
.. code-block:: twig
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
Block Nesting and Scope
-----------------------
Blocks can be nested for more complex layouts. Per default, blocks have access
to variables from outer scopes:
.. code-block:: twig
{% for item in seq %}
{% block loop_item %}{{ item }}{% endblock %}
{% endfor %}
Block Shortcuts
---------------
For blocks with little content, it's possible to use a shortcut syntax. The
following constructs do the same thing:
.. code-block:: twig
{% block title %}
{{ page_title|title }}
{% endblock %}
.. code-block:: twig
{% block title page_title|title %}
Dynamic Inheritance
-------------------
Twig supports dynamic inheritance by using a variable as the base template:
.. code-block:: twig
{% extends some_var %}
If the variable evaluates to a ``\Twig\Template`` or a ``\Twig\TemplateWrapper``
instance, Twig will use it as the parent template::
// {% extends layout %}
$layout = $twig->load('some_layout_template.twig');
$twig->display('template.twig', ['layout' => $layout]);
You can also provide a list of templates that are checked for existence. The
first template that exists will be used as a parent:
.. code-block:: twig
{% extends ['layout.html', 'base_layout.html'] %}
Conditional Inheritance
-----------------------
As the template name for the parent can be any valid Twig expression, it's
possible to make the inheritance mechanism conditional:
.. code-block:: twig
{% extends standalone ? "minimum.html" : "base.html" %}
In this example, the template will extend the "minimum.html" layout template
if the ``standalone`` variable evaluates to ``true``, and "base.html"
otherwise.
How do blocks work?
-------------------
A block provides a way to change how a certain part of a template is rendered
but it does not interfere in any way with the logic around it.
Let's take the following example to illustrate how a block works and more
importantly, how it does not work:
.. code-block:: twig
{# base.twig #}
{% for post in posts %}
{% block post %}
{{ post.title }}
{{ post.body }}
{% endblock %}
{% endfor %}
If you render this template, the result would be exactly the same with or
without the ``block`` tag. The ``block`` inside the ``for`` loop is just a way
to make it overridable by a child template:
.. code-block:: twig
{# child.twig #}
{% extends "base.twig" %}
{% block post %}
{{ post.title }}{{ post.text }}
{% endblock %}
Now, when rendering the child template, the loop is going to use the block
defined in the child template instead of the one defined in the base one; the
executed template is then equivalent to the following one:
.. code-block:: twig
{% for post in posts %}
{{ post.title }}{{ post.text }}
{% endfor %}
Let's take another example: a block included within an ``if`` statement:
.. code-block:: twig
{% if posts is empty %}
{% block head %}
{{ parent() }}
{% endblock head %}
{% endif %}
Contrary to what you might think, this template does not define a block
conditionally; it just makes overridable by a child template the output of
what will be rendered when the condition is ``true``.
If you want the output to be displayed conditionally, use the following
instead:
.. code-block:: twig
{% block head %}
{{ parent() }}
{% if posts is empty %}
{% endif %}
{% endblock head %}
.. seealso:: :doc:`block<../functions/block>`, :doc:`block<../tags/block>`, :doc:`parent<../functions/parent>`, :doc:`use<../tags/use>`
php-twig-2.12.5/doc/tags/filter.rst 0000664 0000000 0000000 00000001214 13624573447 0017077 0 ustar 00root root 0000000 0000000 ``filter``
==========
.. note::
As of Twig 2.9, you should use the ``apply`` tag instead which does the
same thing except that the wrapped template data is not scoped.
Filter sections allow you to apply regular Twig filters on a block of template
data. Just wrap the code in the special ``filter`` section:
.. code-block:: twig
{% filter upper %}
This text becomes uppercase
{% endfilter %}
You can also chain filters and pass arguments to them:
.. code-block:: twig
{% filter lower|escape('html') %}
SOME TEXT
{% endfilter %}
{# outputs "<strong>some text</strong>" #}
php-twig-2.12.5/doc/tags/flush.rst 0000664 0000000 0000000 00000000341 13624573447 0016733 0 ustar 00root root 0000000 0000000 ``flush``
=========
The ``flush`` tag tells Twig to flush the output buffer:
.. code-block:: twig
{% flush %}
.. note::
Internally, Twig uses the PHP `flush`_ function.
.. _`flush`: https://secure.php.net/flush
php-twig-2.12.5/doc/tags/for.rst 0000664 0000000 0000000 00000011320 13624573447 0016377 0 ustar 00root root 0000000 0000000 ``for``
=======
Loop over each item in a sequence. For example, to display a list of users
provided in a variable called ``users``:
.. code-block:: twig
Members
{% for user in users %}
{{ user.username|e }}
{% endfor %}
.. note::
A sequence can be either an array or an object implementing the
``Traversable`` interface.
If you do need to iterate over a sequence of numbers, you can use the ``..``
operator:
.. code-block:: twig
{% for i in 0..10 %}
* {{ i }}
{% endfor %}
The above snippet of code would print all numbers from 0 to 10.
It can be also useful with letters:
.. code-block:: twig
{% for letter in 'a'..'z' %}
* {{ letter }}
{% endfor %}
The ``..`` operator can take any expression at both sides:
.. code-block:: twig
{% for letter in 'a'|upper..'z'|upper %}
* {{ letter }}
{% endfor %}
.. tip:
If you need a step different from 1, you can use the ``range`` function
instead.
The `loop` variable
-------------------
Inside of a ``for`` loop block you can access some special variables:
===================== =============================================================
Variable Description
===================== =============================================================
``loop.index`` The current iteration of the loop. (1 indexed)
``loop.index0`` The current iteration of the loop. (0 indexed)
``loop.revindex`` The number of iterations from the end of the loop (1 indexed)
``loop.revindex0`` The number of iterations from the end of the loop (0 indexed)
``loop.first`` True if first iteration
``loop.last`` True if last iteration
``loop.length`` The number of items in the sequence
``loop.parent`` The parent context
===================== =============================================================
.. code-block:: twig
{% for user in users %}
{{ loop.index }} - {{ user.username }}
{% endfor %}
.. note::
The ``loop.length``, ``loop.revindex``, ``loop.revindex0``, and
``loop.last`` variables are only available for PHP arrays, or objects that
implement the ``Countable`` interface. They are also not available when
looping with a condition.
Adding a condition
------------------
.. tip::
As of Twig 2.10, use the :doc:`filter <../filters/filter>` filter instead,
or an ``if`` condition inside the ``for`` body (if your condition depends on
a variable updated inside the loop and you are not using the ``loop``
variable).
Unlike in PHP, it's not possible to ``break`` or ``continue`` in a loop. You
can however filter the sequence during iteration which allows you to skip
items. The following example skips all the users which are not active:
.. code-block:: twig
{% for user in users if user.active %}
{{ user.username|e }}
{% endfor %}
The advantage is that the special loop variable will count correctly thus not
counting the users not iterated over. Keep in mind that properties like
``loop.last`` will not be defined when using loop conditions.
.. note::
Using the ``loop`` variable within the condition is not recommended as it
will probably not be doing what you expect it to. For instance, adding a
condition like ``loop.index > 4`` won't work as the index is only
incremented when the condition is true (so the condition will never
match).
The `else` Clause
-----------------
If no iteration took place because the sequence was empty, you can render a
replacement block by using ``else``:
.. code-block:: twig
{% for user in users %}
{{ user.username|e }}
{% else %}
no user found
{% endfor %}
Iterating over Keys
-------------------
By default, a loop iterates over the values of the sequence. You can iterate
on keys by using the ``keys`` filter:
.. code-block:: twig
Members
{% for key in users|keys %}
{{ key }}
{% endfor %}
Iterating over Keys and Values
------------------------------
You can also access both keys and values:
.. code-block:: twig
Members
{% for key, user in users %}
{{ key }}: {{ user.username|e }}
{% endfor %}
Iterating over a Subset
-----------------------
You might want to iterate over a subset of values. This can be achieved using
the :doc:`slice <../filters/slice>` filter:
.. code-block:: twig
Top Ten Members
{% for user in users|slice(0, 10) %}
{{ user.username|e }}
{% endfor %}
php-twig-2.12.5/doc/tags/from.rst 0000664 0000000 0000000 00000000310 13624573447 0016551 0 ustar 00root root 0000000 0000000 ``from``
========
The ``from`` tag imports :doc:`macro<../tags/macro>` names into the current
namespace. The tag is documented in detail in the documentation for the
:doc:`macro<../tags/macro>` tag.
php-twig-2.12.5/doc/tags/if.rst 0000664 0000000 0000000 00000003772 13624573447 0016223 0 ustar 00root root 0000000 0000000 ``if``
======
The ``if`` statement in Twig is comparable with the if statements of PHP.
In the simplest form you can use it to test if an expression evaluates to
``true``:
.. code-block:: twig
{% if online == false %}
Our website is in maintenance mode. Please, come back later.
{% endif %}
You can also test if an array is not empty:
.. code-block:: twig
{% if users %}
{% for user in users %}
{{ user.username|e }}
{% endfor %}
{% endif %}
.. note::
If you want to test if the variable is defined, use ``if users is
defined`` instead.
You can also use ``not`` to check for values that evaluate to ``false``:
.. code-block:: twig
{% if not user.subscribed %}
You are not subscribed to our mailing list.
{% endif %}
For multiple conditions, ``and`` and ``or`` can be used:
.. code-block:: twig
{% if temperature > 18 and temperature < 27 %}
It's a nice day for a walk in the park.
{% endif %}
For multiple branches ``elseif`` and ``else`` can be used like in PHP. You can
use more complex ``expressions`` there too:
.. code-block:: twig
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
Only {{ product.stock }} left!
{% else %}
Sold-out!
{% endif %}
.. note::
The rules to determine if an expression is ``true`` or ``false`` are the
same as in PHP; here are the edge cases rules:
====================== ====================
Value Boolean evaluation
====================== ====================
empty string false
numeric zero false
NAN (Not A Number) true
INF (Infinity) true
whitespace-only string true
string "0" or '0' false
empty array false
null false
non-empty array true
object true
====================== ====================
php-twig-2.12.5/doc/tags/import.rst 0000664 0000000 0000000 00000000307 13624573447 0017126 0 ustar 00root root 0000000 0000000 ``import``
==========
The ``import`` tag imports :doc:`macro<../tags/macro>` names in a local
variable. The tag is documented in detail in the documentation for the
:doc:`macro<../tags/macro>` tag.
php-twig-2.12.5/doc/tags/include.rst 0000664 0000000 0000000 00000006673 13624573447 0017253 0 ustar 00root root 0000000 0000000 ``include``
===========
The ``include`` statement includes a template and returns the rendered content
of that file:
.. code-block:: twig
{% include 'header.html' %}
Body
{% include 'footer.html' %}
.. note::
As of Twig 1.12, it is recommended to use the
:doc:`include<../functions/include>` function instead as it provides the
same features with a bit more flexibility:
* The ``include`` function is semantically more "correct" (including a
template outputs its rendered contents in the current scope; a tag should
not display anything);
* The ``include`` function is more "composable":
.. code-block:: twig
{# Store a rendered template in a variable #}
{% set content %}
{% include 'template.html' %}
{% endset %}
{# vs #}
{% set content = include('template.html') %}
{# Filter a rendered template #}
{% filter upper %}
{% include 'template.html' %}
{% endfilter %}
{# vs #}
{{ include('template.html')|upper }}
* The ``include`` function does not impose any specific order for
arguments thanks to :ref:`named arguments `.
Included templates have access to the variables of the active context.
If you are using the filesystem loader, the templates are looked for in the
paths defined by it.
You can add additional variables by passing them after the ``with`` keyword:
.. code-block:: twig
{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}
{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}
You can disable access to the context by appending the ``only`` keyword:
.. code-block:: twig
{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}
.. code-block:: twig
{# no variables will be accessible #}
{% include 'template.html' only %}
.. tip::
When including a template created by an end user, you should consider
sandboxing it. More information in the :doc:`Twig for Developers<../api>`
chapter and in the :doc:`sandbox<../tags/sandbox>` tag documentation.
The template name can be any valid Twig expression:
.. code-block:: twig
{% include some_var %}
{% include ajax ? 'ajax.html' : 'not_ajax.html' %}
And if the expression evaluates to a ``\Twig\Template`` or a
``\Twig\TemplateWrapper`` instance, Twig will use it directly::
// {% include template %}
$template = $twig->load('some_template.twig');
$twig->display('template.twig', ['template' => $template]);
You can mark an include with ``ignore missing`` in which case Twig will ignore
the statement if the template to be included does not exist. It has to be
placed just after the template name. Here some valid examples:
.. code-block:: twig
{% include 'sidebar.html' ignore missing %}
{% include 'sidebar.html' ignore missing with {'foo': 'bar'} %}
{% include 'sidebar.html' ignore missing only %}
You can also provide a list of templates that are checked for existence before
inclusion. The first template that exists will be included:
.. code-block:: twig
{% include ['page_detailed.html', 'page.html'] %}
If ``ignore missing`` is given, it will fall back to rendering nothing if none
of the templates exist, otherwise it will throw an exception.
php-twig-2.12.5/doc/tags/index.rst 0000664 0000000 0000000 00000000407 13624573447 0016724 0 ustar 00root root 0000000 0000000 Tags
====
.. toctree::
:maxdepth: 1
apply
autoescape
block
deprecated
do
embed
extends
filter
flush
for
from
if
import
include
macro
sandbox
set
spaceless
use
verbatim
with
php-twig-2.12.5/doc/tags/macro.rst 0000664 0000000 0000000 00000012607 13624573447 0016723 0 ustar 00root root 0000000 0000000 ``macro``
=========
Macros are comparable with functions in regular programming languages. They
are useful to reuse template fragments to not repeat yourself.
Macros are defined in regular templates.
Imagine having a generic helper template that define how to render HTML forms
via macros (called ``forms.html``):
.. code-block:: twig
{% macro input(name, value, type = "text", size = 20) %}
{% endmacro %}
{% macro textarea(name, value, rows = 10, cols = 40) %}
{% endmacro %}
Each macro argument can have a default value (here ``text`` is the default value
for ``type`` if not provided in the call).
Macros differ from native PHP functions in a few ways:
* Arguments of a macro are always optional.
* If extra positional arguments are passed to a macro, they end up in the
special ``varargs`` variable as a list of values.
But as with PHP functions, macros don't have access to the current template
variables.
.. tip::
You can pass the whole context as an argument by using the special
``_context`` variable.
Importing Macros
----------------
There are two ways to import macros. You can import the complete template
containing the macros into a local variable (via the ``import`` tag) or only
import specific macros from the template (via the ``from`` tag).
To import all macros from a template into a local variable, use the ``import``
tag:
.. code-block:: twig
{% import "forms.html" as forms %}
The above ``import`` call imports the ``forms.html`` file (which can contain
only macros, or a template and some macros), and import the macros as items of
the ``forms`` local variable.
The macros can then be called at will in the *current* template:
.. code-block:: twig
{{ forms.input('username') }}
{{ forms.input('password', null, 'password') }}
Alternatively you can import names from the template into the current namespace
via the ``from`` tag:
.. code-block:: twig
{% from 'forms.html' import input as input_field, textarea %}
{{ input_field('password', '', 'password') }}
{{ textarea('comment') }}
.. tip::
When macro usages and definitions are in the same template, you don't need to
import the macros as they are automatically available under the special
``_self`` variable:
.. code-block:: twig
{{ _self.input('password', '', 'password') }}
{% macro input(name, value, type = "text", size = 20) %}
{% endmacro %}
Auto-import is only available as of Twig 2.11. For older versions, import
macros using the special ``_self`` variable for the template name:
.. code-block:: twig
{% import _self as forms %}
{{ forms.input('username') }}
.. note::
Before Twig 2.11, when you want to use a macro in another macro from the
same file, you need to import it locally:
.. code-block:: twig
{% macro input(name, value, type, size) %}
{% endmacro %}
{% macro wrapped_input(name, value, type, size) %}
{% import _self as forms %}
{{ forms.input(name, value, type, size) }}
{% endmacro %}
Macros Scoping
--------------
.. versionadded:: 2.11
The scoping rules described in this paragraph are implemented as of Twig
2.11.
The scoping rules are the same whether you imported macros via ``import`` or
``from``.
Imported macros are always **local** to the current template. It means that
macros are available in all blocks and other macros defined in the current
template, but they are not available in included templates or child templates;
you need to explicitely re-import macros in each template.
When calling ``import`` or ``from`` from a ``block`` tag, the imported macros
are only defined in the current block and they override macros defined at the
template level with the same names.
When calling ``import`` or ``from`` from a ``macro`` tag, the imported macros
are only defined in the current macro and they override macros defined at the
template level with the same names.
.. note::
Before Twig 2.11, it was possible to use macros imported in a block in a
"sub-block". When upgrading to 2.11, you need to either move the import in
the global scope or reimport the macros explicitly in the "sub-blocks".
Checking if a Macro is defined
------------------------------
.. versionadded:: 2.11
Support for the ``defined`` test on macros was added in Twig 2.11.
You can check if a macro is defined via the ``defined`` test:
.. code-block:: twig
{% import "macros.twig" as macros %}
{% from "macros.twig" import hello %}
{% if macros.hello is defined -%}
OK
{% endif %}
{% if hello is defined -%}
OK
{% endif %}
Named Macro End-Tags
--------------------
Twig allows you to put the name of the macro after the end tag for better
readability (the name after the ``endmacro`` word must match the macro name):
.. code-block:: twig
{% macro input() %}
...
{% endmacro input %}
php-twig-2.12.5/doc/tags/sandbox.rst 0000664 0000000 0000000 00000001372 13624573447 0017255 0 ustar 00root root 0000000 0000000 ``sandbox``
===========
The ``sandbox`` tag can be used to enable the sandboxing mode for an included
template, when sandboxing is not enabled globally for the Twig environment:
.. code-block:: twig
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
.. warning::
The ``sandbox`` tag is only available when the sandbox extension is
enabled (see the :doc:`Twig for Developers<../api>` chapter).
.. note::
The ``sandbox`` tag can only be used to sandbox an include tag and it
cannot be used to sandbox a section of a template. The following example
won't work:
.. code-block:: twig
{% sandbox %}
{% for i in 1..2 %}
{{ i }}
{% endfor %}
{% endsandbox %}
php-twig-2.12.5/doc/tags/set.rst 0000664 0000000 0000000 00000003212 13624573447 0016405 0 ustar 00root root 0000000 0000000 ``set``
=======
Inside code blocks you can also assign values to variables. Assignments use
the ``set`` tag and can have multiple targets.
Here is how you can assign the ``bar`` value to the ``foo`` variable:
.. code-block:: twig
{% set foo = 'bar' %}
After the ``set`` call, the ``foo`` variable is available in the template like
any other ones:
.. code-block:: twig
{# displays bar #}
{{ foo }}
The assigned value can be any valid :ref:`Twig expression
`:
.. code-block:: twig
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
Several variables can be assigned in one block:
.. code-block:: twig
{% set foo, bar = 'foo', 'bar' %}
{# is equivalent to #}
{% set foo = 'foo' %}
{% set bar = 'bar' %}
The ``set`` tag can also be used to 'capture' chunks of text:
.. code-block:: twig
{% set foo %}
...
{% endset %}
.. caution::
If you enable automatic output escaping, Twig will only consider the
content to be safe when capturing chunks of text.
.. note::
Note that loops are scoped in Twig; therefore a variable declared inside a
``for`` loop is not accessible outside the loop itself:
.. code-block:: twig
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# foo is NOT available #}
If you want to access the variable, just declare it before the loop:
.. code-block:: twig
{% set foo = "" %}
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# foo is available #}
php-twig-2.12.5/doc/tags/spaceless.rst 0000664 0000000 0000000 00000002363 13624573447 0017602 0 ustar 00root root 0000000 0000000 ``spaceless``
=============
.. tip::
As of Twig 1.38, use the :doc:`spaceless <../filters/spaceless>` filter instead.
Use the ``spaceless`` tag to remove whitespace *between HTML tags*, not
whitespace within HTML tags or whitespace in plain text:
.. code-block:: twig
{% spaceless %}
foo
{% endspaceless %}
{# output will be
foo
#}
This tag is not meant to "optimize" the size of the generated HTML content but
merely to avoid extra whitespace between HTML tags to avoid browser rendering
quirks under some circumstances.
.. tip::
If you want to optimize the size of the generated HTML content, gzip
compress the output instead.
.. tip::
If you want to create a tag that actually removes all extra whitespace in
an HTML string, be warned that this is not as easy as it seems to be
(think of ``textarea`` or ``pre`` tags for instance). Using a third-party
library like Tidy is probably a better idea.
.. tip::
For more information on whitespace control, read the
:ref:`dedicated section ` of the documentation and learn how
you can also use the whitespace control modifier on your tags.
php-twig-2.12.5/doc/tags/use.rst 0000664 0000000 0000000 00000006266 13624573447 0016422 0 ustar 00root root 0000000 0000000 ``use``
=======
.. note::
Horizontal reuse is an advanced Twig feature that is hardly ever needed in
regular templates. It is mainly used by projects that need to make
template blocks reusable without using inheritance.
Template inheritance is one of the most powerful features of Twig but it is
limited to single inheritance; a template can only extend one other template.
This limitation makes template inheritance simple to understand and easy to
debug:
.. code-block:: twig
{% extends "base.html" %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
Horizontal reuse is a way to achieve the same goal as multiple inheritance,
but without the associated complexity:
.. code-block:: twig
{% extends "base.html" %}
{% use "blocks.html" %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
The ``use`` statement tells Twig to import the blocks defined in
``blocks.html`` into the current template (it's like macros, but for blocks):
.. code-block:: twig
{# blocks.html #}
{% block sidebar %}{% endblock %}
In this example, the ``use`` statement imports the ``sidebar`` block into the
main template. The code is mostly equivalent to the following one (the
imported blocks are not outputted automatically):
.. code-block:: twig
{% extends "base.html" %}
{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
.. note::
The ``use`` tag only imports a template if it does not extend another
template, if it does not define macros, and if the body is empty. But it
can *use* other templates.
.. note::
Because ``use`` statements are resolved independently of the context
passed to the template, the template reference cannot be an expression.
The main template can also override any imported block. If the template
already defines the ``sidebar`` block, then the one defined in ``blocks.html``
is ignored. To avoid name conflicts, you can rename imported blocks:
.. code-block:: twig
{% extends "base.html" %}
{% use "blocks.html" with sidebar as base_sidebar, title as base_title %}
{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
The ``parent()`` function automatically determines the correct inheritance
tree, so it can be used when overriding a block defined in an imported
template:
.. code-block:: twig
{% extends "base.html" %}
{% use "blocks.html" %}
{% block sidebar %}
{{ parent() }}
{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
In this example, ``parent()`` will correctly call the ``sidebar`` block from
the ``blocks.html`` template.
.. tip::
Renaming allows you to simulate inheritance by calling the "parent" block:
.. code-block:: twig
{% extends "base.html" %}
{% use "blocks.html" with sidebar as parent_sidebar %}
{% block sidebar %}
{{ block('parent_sidebar') }}
{% endblock %}
.. note::
You can use as many ``use`` statements as you want in any given template.
If two imported templates define the same block, the latest one wins.
php-twig-2.12.5/doc/tags/verbatim.rst 0000664 0000000 0000000 00000000556 13624573447 0017433 0 ustar 00root root 0000000 0000000 ``verbatim``
============
The ``verbatim`` tag marks sections as being raw text that should not be
parsed. For example to put Twig syntax as example into a template you can use
this snippet:
.. code-block:: twig
{% verbatim %}
{% for item in seq %}
{{ item }}
{% endfor %}
{% endverbatim %}
php-twig-2.12.5/doc/tags/with.rst 0000664 0000000 0000000 00000002074 13624573447 0016572 0 ustar 00root root 0000000 0000000 ``with``
========
Use the ``with`` tag to create a new inner scope. Variables set within this
scope are not visible outside of the scope:
.. code-block:: twig
{% with %}
{% set foo = 42 %}
{{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer
Instead of defining variables at the beginning of the scope, you can pass a
hash of variables you want to define in the ``with`` tag; the previous example
is equivalent to the following one:
.. code-block:: twig
{% with { foo: 42 } %}
{{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer
{# it works with any expression that resolves to a hash #}
{% set vars = { foo: 42 } %}
{% with vars %}
...
{% endwith %}
By default, the inner scope has access to the outer scope context; you can
disable this behavior by appending the ``only`` keyword:
.. code-block:: twig
{% set bar = 'bar' %}
{% with { foo: 42 } only %}
{# only foo is defined #}
{# bar is not defined #}
{% endwith %}
php-twig-2.12.5/doc/templates.rst 0000664 0000000 0000000 00000062407 13624573447 0016665 0 ustar 00root root 0000000 0000000 Twig for Template Designers
===========================
This document describes the syntax and semantics of the template engine and
will be most useful as reference to those creating Twig templates.
Synopsis
--------
A template is a regular text file. It can generate any text-based format (HTML,
XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
``.xml`` are just fine.
A template contains **variables** or **expressions**, which get replaced with
values when the template is evaluated, and **tags**, which control the
template's logic.
Below is a minimal template that illustrates a few basics. We will cover further
details later on:
.. code-block:: html+twig
My Webpage
{{ a_variable }}
There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
one is used to execute statements such as for-loops, the latter outputs the
result of an expression.
IDEs Integration
----------------
Many IDEs support syntax highlighting and auto-completion for Twig:
* *Textmate* via the `Twig bundle`_
* *Vim* via the `Jinja syntax plugin`_ or the `vim-twig plugin`_
* *Netbeans* via the `Twig syntax plugin`_ (until 7.1, native as of 7.2)
* *PhpStorm* (native as of 2.1)
* *Eclipse* via the `Twig plugin`_
* *Sublime Text* via the `Twig bundle`_
* *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects)
* *Coda* and *SubEthaEdit* via the `Twig syntax mode`_
* *Coda 2* via the `other Twig syntax mode`_
* *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode
* *Notepad++* via the `Notepad++ Twig Highlighter`_
* *Emacs* via `web-mode.el`_
* *Atom* via the `PHP-twig for atom`_
* *Visual Studio Code* via the `Twig pack`_
Also, `TwigFiddle`_ is an online service that allows you to execute Twig templates
from a browser; it supports all versions of Twig.
Variables
---------
The application passes variables to the templates for manipulation in the
template. Variables may have attributes or elements you can access, too. The
visual representation of a variable depends heavily on the application providing
it.
Use a dot (``.``) to access attributes of a variable (methods or properties of a
PHP object, or items of a PHP array):
.. code-block:: twig
{{ foo.bar }}
.. note::
It's important to know that the curly braces are *not* part of the
variable but the print statement. When accessing variables inside tags,
don't put the braces around them.
.. sidebar:: Implementation
For convenience's sake ``foo.bar`` does the following things on the PHP
layer:
* check if ``foo`` is an array and ``bar`` a valid element;
* if not, and if ``foo`` is an object, check that ``bar`` is a valid property;
* if not, and if ``foo`` is an object, check that ``bar`` is a valid method
(even if ``bar`` is the constructor - use ``__construct()`` instead);
* if not, and if ``foo`` is an object, check that ``getBar`` is a valid method;
* if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
* if not, and if ``foo`` is an object, check that ``hasBar`` is a valid method;
* if not, return a ``null`` value.
Twig also supports a specific syntax for accessing items on PHP arrays,
``foo['bar']``:
* check if ``foo`` is an array and ``bar`` a valid element;
* if not, return a ``null`` value.
If a variable or attribute does not exist, you will receive a ``null`` value
when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
is set, Twig will throw an error (see :ref:`environment options`).
.. note::
If you want to access a dynamic attribute of a variable, use the
:doc:`attribute` function instead.
The ``attribute`` function is also useful when the attribute contains
special characters (like ``-`` that would be interpreted as the minus
operator):
.. code-block:: twig
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
Global Variables
~~~~~~~~~~~~~~~~
The following variables are always available in templates:
* ``_self``: references the current template name;
* ``_context``: references the current context;
* ``_charset``: references the current charset.
Setting Variables
~~~~~~~~~~~~~~~~~
You can assign values to variables inside code blocks. Assignments use the
:doc:`set` tag:
.. code-block:: twig
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
Filters
-------
Variables can be modified by **filters**. Filters are separated from the
variable by a pipe symbol (``|``). Multiple filters can be chained. The output
of one filter is applied to the next.
The following example removes all HTML tags from the ``name`` and title-cases
it:
.. code-block:: twig
{{ name|striptags|title }}
Filters that accept arguments have parentheses around the arguments. This
example joins the elements of a list by commas:
.. code-block:: twig
{{ list|join(', ') }}
To apply a filter on a section of code, wrap it with the
:doc:`apply` tag:
.. code-block:: twig
{% apply upper %}
This text becomes uppercase
{% endapply %}
Go to the :doc:`filters` page to learn more about built-in
filters.
.. note::
The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with
previous versions.
Functions
---------
Functions can be called to generate content. Functions are called by their
name followed by parentheses (``()``) and may have arguments.
For instance, the ``range`` function returns a list containing an arithmetic
progression of integers:
.. code-block:: twig
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
Go to the :doc:`functions` page to learn more about the
built-in functions.
.. _named-arguments:
Named Arguments
---------------
.. code-block:: twig
{% for i in range(low=1, high=10, step=2) %}
{{ i }},
{% endfor %}
Using named arguments makes your templates more explicit about the meaning of
the values you pass as arguments:
.. code-block:: twig
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
{# versus #}
{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
Named arguments also allow you to skip some arguments for which you don't want
to change the default value:
.. code-block:: twig
{# the first argument is the date format, which defaults to the global date format if null is passed #}
{{ "now"|date(null, "Europe/Paris") }}
{# or skip the format value by using a named argument for the time zone #}
{{ "now"|date(timezone="Europe/Paris") }}
You can also use both positional and named arguments in one call, in which
case positional arguments must always come before named arguments:
.. code-block:: twig
{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
.. tip::
Each function and filter documentation page has a section where the names
of all arguments are listed when supported.
Control Structure
-----------------
A control structure refers to all those things that control the flow of a
program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as
well as things like blocks. Control structures appear inside ``{% ... %}``
blocks.
For example, to display a list of users provided in a variable called
``users``, use the :doc:`for` tag:
.. code-block:: twig
Members
{% for user in users %}
{{ user.username|e }}
{% endfor %}
The :doc:`if` tag can be used to test an expression:
.. code-block:: twig
{% if users|length > 0 %}
{% for user in users %}
{{ user.username|e }}
{% endfor %}
{% endif %}
Go to the :doc:`tags` page to learn more about the built-in tags.
Comments
--------
To comment-out part of a line in a template, use the comment syntax ``{# ...
#}``. This is useful for debugging or to add information for other template
designers or yourself:
.. code-block:: twig
{# note: disabled template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}
Including other Templates
-------------------------
The :doc:`include` function is useful to include a template
and return the rendered content of that template into the current one:
.. code-block:: twig
{{ include('sidebar.html') }}
By default, included templates have access to the same context as the template
which includes them. This means that any variable defined in the main template
will be available in the included template too:
.. code-block:: twig
{% for box in boxes %}
{{ include('render_box.html') }}
{% endfor %}
The included template ``render_box.html`` is able to access the ``box`` variable.
The name of the template depends on the template loader. For instance, the
``\Twig\Loader\FilesystemLoader`` allows you to access other templates by giving the
filename. You can access templates in subdirectories with a slash:
.. code-block:: twig
{{ include('sections/articles/sidebar.html') }}
This behavior depends on the application embedding Twig.
Template Inheritance
--------------------
The most powerful part of Twig is template inheritance. Template inheritance
allows you to build a base "skeleton" template that contains all the common
elements of your site and defines **blocks** that child templates can
override.
It's easier to understand the concept by starting with an example.
Let's define a base template, ``base.html``, which defines an HTML skeleton
document that might be used for a two-column page:
.. code-block:: html+twig
{% block head %}
{% block title %}{% endblock %} - My Webpage
{% endblock %}
{% block content %}{% endblock %}
In this example, the :doc:`block` tags define four blocks that
child templates can fill in. All the ``block`` tag does is to tell the
template engine that a child template may override those portions of the
template.
A child template might look like this:
.. code-block:: twig
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
{% endblock %}
{% block content %}
Index
Welcome to my awesome homepage.
{% endblock %}
The :doc:`extends` tag is the key here. It tells the template
engine that this template "extends" another template. When the template system
evaluates this template, first it locates the parent. The extends tag should
be the first tag in the template.
Note that since the child template doesn't define the ``footer`` block, the
value from the parent template is used instead.
It's possible to render the contents of the parent block by using the
:doc:`parent` function. This gives back the results of the
parent block:
.. code-block:: twig
{% block sidebar %}
Table Of Contents
...
{{ parent() }}
{% endblock %}
.. tip::
The documentation page for the :doc:`extends` tag describes
more advanced features like block nesting, scope, dynamic inheritance, and
conditional inheritance.
.. note::
Twig also supports multiple inheritance via "horizontal reuse" with the help
of the :doc:`use` tag.
HTML Escaping
-------------
When generating HTML from templates, there's always a risk that a variable
will include characters that affect the resulting HTML. There are two
approaches: manually escaping each variable or automatically escaping
everything by default.
Twig supports both, automatic escaping is enabled by default.
The automatic escaping strategy can be configured via the
:ref:`autoescape` option and defaults to ``html``.
Working with Manual Escaping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If manual escaping is enabled, it is **your** responsibility to escape variables
if needed. What to escape? Any variable that comes from an untrusted source.
Escaping works by using the :doc:`escape` or ``e`` filter:
.. code-block:: twig
{{ user.username|e }}
By default, the ``escape`` filter uses the ``html`` strategy, but depending on
the escaping context, you might want to explicitly use an other strategy:
.. code-block:: twig
{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}
Working with Automatic Escaping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whether automatic escaping is enabled or not, you can mark a section of a
template to be escaped or not by using the :doc:`autoescape`
tag:
.. code-block:: twig
{% autoescape %}
Everything will be automatically escaped in this block (using the HTML strategy)
{% endautoescape %}
By default, auto-escaping uses the ``html`` escaping strategy. If you output
variables in other contexts, you need to explicitly escape them with the
appropriate escaping strategy:
.. code-block:: twig
{% autoescape 'js' %}
Everything will be automatically escaped in this block (using the JS strategy)
{% endautoescape %}
Escaping
--------
It is sometimes desirable or even necessary to have Twig ignore parts it would
otherwise handle as variables or blocks. For example if the default syntax is
used and you want to use ``{{`` as raw string in the template and not start a
variable you have to use a trick.
The easiest way is to output the variable delimiter (``{{``) by using a variable
expression:
.. code-block:: twig
{{ '{{' }}
For bigger sections it makes sense to mark a block
:doc:`verbatim`.
Macros
------
Macros are comparable with functions in regular programming languages. They are
useful to reuse HTML fragments to not repeat yourself. They are described in the
:doc:`macro` tag documentation.
.. _twig-expressions:
Expressions
-----------
Twig allows expressions everywhere.
.. note::
The operator precedence is as follows, with the lowest-precedence operators
listed first: ``?:`` (ternary operator), ``b-and``, ``b-xor``, ``b-or``,
``or``, ``and``, ``==``, ``!=``, ``<=>``, ``<``, ``>``, ``>=``, ``<=``,
``in``, ``matches``, ``starts with``, ``ends with``, ``..``, ``+``, ``-``,
``~``, ``*``, ``/``, ``//``, ``%``, ``is`` (tests), ``**``, ``??``, ``|``
(filters), ``[]``, and ``.``:
.. code-block:: twig
{% set greeting = 'Hello ' %}
{% set name = 'Fabien' %}
{{ greeting ~ name|lower }} {# Hello fabien #}
{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}
Literals
~~~~~~~~
The simplest form of expressions are literals. Literals are representations
for PHP types such as strings, numbers, and arrays. The following literals
exist:
* ``"Hello World"``: Everything between two double or single quotes is a
string. They are useful whenever you need a string in the template (for
example as arguments to function calls, filters or just to extend or include
a template). A string can contain a delimiter if it is preceded by a
backslash (``\``) -- like in ``'It\'s good'``. If the string contains a
backslash (e.g. ``'c:\Program Files'``) escape it by doubling it
(e.g. ``'c:\\Program Files'``).
* ``42`` / ``42.23``: Integers and floating point numbers are created by
writing the number down. If a dot is present the number is a float,
otherwise an integer.
* ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
separated by a comma (``,``) and wrapped with squared brackets (``[]``).
* ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
separated by a comma (``,``) and wrapped with curly braces (``{}``):
.. code-block:: twig
{# keys as string #}
{ 'foo': 'foo', 'bar': 'bar' }
{# keys as names (equivalent to the previous hash) #}
{ foo: 'foo', bar: 'bar' }
{# keys as integer #}
{ 2: 'foo', 4: 'bar' }
{# keys as expressions (the expression must be enclosed into parentheses) #}
{% set foo = 'foo' %}
{ (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
* ``true`` / ``false``: ``true`` represents the true value, ``false``
represents the false value.
* ``null``: ``null`` represents no specific value. This is the value returned
when a variable does not exist. ``none`` is an alias for ``null``.
Arrays and hashes can be nested:
.. code-block:: twig
{% set foo = [1, {"foo": "bar"}] %}
.. tip::
Using double-quoted or single-quoted strings has no impact on performance
but :ref:`string interpolation ` is only
supported in double-quoted strings.
Math
~~~~
Twig allows you to do math in templates; the following operators are supported:
* ``+``: Adds two numbers together (the operands are casted to numbers). ``{{
1 + 1 }}`` is ``2``.
* ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
``1``.
* ``/``: Divides two numbers. The returned value will be a floating point
number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
* ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
``4``.
* ``//``: Divides two numbers and returns the floored integer result. ``{{ 20
// 7 }}`` is ``2``, ``{{ -20 // 7 }}`` is ``-3`` (this is just syntactic
sugar for the :doc:`round` filter).
* ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
return ``4``.
* ``**``: Raises the left operand to the power of the right operand. ``{{ 2 **
3 }}`` would return ``8``.
.. _template_logic:
Logic
~~~~~
You can combine multiple expressions with the following operators:
* ``and``: Returns true if the left and the right operands are both true.
* ``or``: Returns true if the left or the right operand is true.
* ``not``: Negates a statement.
* ``(expr)``: Groups an expression.
.. note::
Twig also supports bitwise operators (``b-and``, ``b-xor``, and ``b-or``).
.. note::
Operators are case sensitive.
Comparisons
~~~~~~~~~~~
The following comparison operators are supported in any expression: ``==``,
``!=``, ``<``, ``>``, ``>=``, and ``<=``.
You can also check if a string ``starts with`` or ``ends with`` another
string:
.. code-block:: twig
{% if 'Fabien' starts with 'F' %}
{% endif %}
{% if 'Fabien' ends with 'n' %}
{% endif %}
.. note::
For complex string comparisons, the ``matches`` operator allows you to use
`regular expressions`_:
.. code-block:: twig
{% if phone matches '/^[\\d\\.]+$/' %}
{% endif %}
Containment Operator
~~~~~~~~~~~~~~~~~~~~
The ``in`` operator performs containment test. It returns ``true`` if the left
operand is contained in the right:
.. code-block:: twig
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
.. tip::
You can use this filter to perform a containment test on strings, arrays,
or objects implementing the ``Traversable`` interface.
To perform a negative test, use the ``not in`` operator:
.. code-block:: twig
{% if 1 not in [1, 2, 3] %}
{# is equivalent to #}
{% if not (1 in [1, 2, 3]) %}
Test Operator
~~~~~~~~~~~~~
The ``is`` operator performs tests. Tests can be used to test a variable against
a common expression. The right operand is name of the test:
.. code-block:: twig
{# find out if a variable is odd #}
{{ name is odd }}
Tests can accept arguments too:
.. code-block:: twig
{% if post.status is constant('Post::PUBLISHED') %}
Tests can be negated by using the ``is not`` operator:
.. code-block:: twig
{% if post.status is not constant('Post::PUBLISHED') %}
{# is equivalent to #}
{% if not (post.status is constant('Post::PUBLISHED')) %}
Go to the :doc:`tests` page to learn more about the built-in
tests.
Other Operators
~~~~~~~~~~~~~~~
The following operators don't fit into any of the other categories:
* ``|``: Applies a filter.
* ``..``: Creates a sequence based on the operand before and after the operator
(this is syntactic sugar for the :doc:`range` function):
.. code-block:: twig
{{ 1..5 }}
{# equivalent to #}
{{ range(1, 5) }}
Note that you must use parentheses when combining it with the filter operator
due to the :ref:`operator precedence rules `:
.. code-block:: twig
(1..5)|join(', ')
* ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
" ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
John!``.
* ``.``, ``[]``: Gets an attribute of a variable.
* ``?:``: The ternary operator:
.. code-block:: twig
{{ foo ? 'yes' : 'no' }}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
* ``??``: The null-coalescing operator:
.. code-block:: twig
{# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }}
.. _templates-string-interpolation:
String Interpolation
~~~~~~~~~~~~~~~~~~~~
String interpolation (``#{expression}``) allows any valid expression to appear
within a *double-quoted string*. The result of evaluating that expression is
inserted into the string:
.. code-block:: twig
{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}
.. _templates-whitespace-control:
Whitespace Control
------------------
.. versionadded:: 2.8
Tag level Line whitespace control was added in Twig 2.8.
The first newline after a template tag is removed automatically (like in PHP).
Whitespace is not further modified by the template engine, so each whitespace
(spaces, tabs, newlines etc.) is returned unchanged.
You can also control whitespace on a per tag level. By using the whitespace
control modifiers on your tags, you can trim leading and or trailing whitespace.
Twig supports two modifiers:
* *Whitespace trimming* via the ``-`` modifier: Removes all whitespace
(including newlines);
* *Line whitespace trimming* via the ``~`` modifier: Removes all whitespace
(excluding newlines). Using this modifier on the right disables the default
removal of the first newline inherited from PHP.
The modifiers can be used on either side of the tags like in ``{%-`` or ``-%}``
and they consume all whitespace for that side of the tag. It is possible to use
the modifiers on one side of a tag or on both sides:
.. code-block:: twig
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
{{- value -}}
{%- endif -%}
{# output 'no spaces' #}
{{ value }}
{# outputs '
\n no spaces
' #}
{{- value }}
{# outputs '
no spaces
' #}
{{~ value }}
{# outputs '
\nno spaces
' #}
.. tip::
In addition to the whitespace modifiers, Twig also has a ``spaceless`` filter
that removes whitespace **between HTML tags**:
.. code-block:: twig
{% apply spaceless %}
foo bar
{% endapply %}
{# output will be
foo bar
#}
The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with
previous versions.
Extensions
----------
Twig can be extended. If you want to create your own extensions, read the
:ref:`Creating an Extension ` chapter.
.. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle
.. _`Jinja syntax plugin`: http://jinja.pocoo.org/docs/integration/#vim
.. _`vim-twig plugin`: https://github.com/lumiliet/vim-twig
.. _`Twig syntax plugin`: http://plugins.netbeans.org/plugin/37069/php-twig
.. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin
.. _`Twig language definition`: https://github.com/gabrielcorpse/gedit-twig-template-language
.. _`Twig syntax mode`: https://github.com/bobthecow/Twig-HTML.mode
.. _`other Twig syntax mode`: https://github.com/muxx/Twig-HTML.mode
.. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig
.. _`web-mode.el`: http://web-mode.org/
.. _`regular expressions`: https://secure.php.net/manual/en/pcre.pattern.php
.. _`PHP-twig for atom`: https://github.com/reesef/php-twig
.. _`TwigFiddle`: https://twigfiddle.com/
.. _`Twig pack`: https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack
php-twig-2.12.5/doc/tests/ 0000775 0000000 0000000 00000000000 13624573447 0015266 5 ustar 00root root 0000000 0000000 php-twig-2.12.5/doc/tests/constant.rst 0000664 0000000 0000000 00000001032 13624573447 0017645 0 ustar 00root root 0000000 0000000 ``constant``
============
``constant`` checks if a variable has the exact same value as a constant. You
can use either global constants or class constants:
.. code-block:: twig
{% if post.status is constant('Post::PUBLISHED') %}
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
You can test constants from object instances as well:
.. code-block:: twig
{% if post.status is constant('PUBLISHED', post) %}
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
php-twig-2.12.5/doc/tests/defined.rst 0000664 0000000 0000000 00000001264 13624573447 0017421 0 ustar 00root root 0000000 0000000 ``defined``
===========
``defined`` checks if a variable is defined in the current context. This is very
useful if you use the ``strict_variables`` option:
.. code-block:: twig
{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}
{% if foo['bar'] is defined %}
...
{% endif %}
When using the ``defined`` test on an expression that uses variables in some
method calls, be sure that they are all defined first:
.. code-block:: twig
{% if var is defined and foo.method(var) is defined %}
...
{% endif %}
php-twig-2.12.5/doc/tests/divisibleby.rst 0000664 0000000 0000000 00000000301 13624573447 0020317 0 ustar 00root root 0000000 0000000 ``divisible by``
================
``divisible by`` checks if a variable is divisible by a number:
.. code-block:: twig
{% if loop.index is divisible by(3) %}
...
{% endif %}
php-twig-2.12.5/doc/tests/empty.rst 0000664 0000000 0000000 00000001102 13624573447 0017150 0 ustar 00root root 0000000 0000000 ``empty``
=========
.. versionadded:: 2.3
Support for the ``__toString()`` magic method has been added in Twig 2.3.
``empty`` checks if a variable is an empty string, an empty array, an empty
hash, exactly ``false``, or exactly ``null``.
For objects that implement the ``Countable`` interface, ``empty`` will check the
return value of the ``count()`` method.
For objects that implement the ``__toString()`` magic method (and not ``Countable``),
it will check if an empty string is returned.
.. code-block:: twig
{% if foo is empty %}
...
{% endif %}
php-twig-2.12.5/doc/tests/even.rst 0000664 0000000 0000000 00000000236 13624573447 0016756 0 ustar 00root root 0000000 0000000 ``even``
========
``even`` returns ``true`` if the given number is even:
.. code-block:: twig
{{ var is even }}
.. seealso:: :doc:`odd<../tests/odd>`
php-twig-2.12.5/doc/tests/index.rst 0000664 0000000 0000000 00000000221 13624573447 0017122 0 ustar 00root root 0000000 0000000 Tests
=====
.. toctree::
:maxdepth: 1
constant
defined
divisibleby
empty
even
iterable
null
odd
sameas
php-twig-2.12.5/doc/tests/iterable.rst 0000664 0000000 0000000 00000000612 13624573447 0017606 0 ustar 00root root 0000000 0000000 ``iterable``
============
``iterable`` checks if a variable is an array or a traversable object:
.. code-block:: twig
{# evaluates to true if the foo variable is iterable #}
{% if users is iterable %}
{% for user in users %}
Hello {{ user }}!
{% endfor %}
{% else %}
{# users is probably a string #}
Hello {{ users }}!
{% endif %}
php-twig-2.12.5/doc/tests/null.rst 0000664 0000000 0000000 00000000252 13624573447 0016771 0 ustar 00root root 0000000 0000000 ``null``
========
``null`` returns ``true`` if the variable is ``null``:
.. code-block:: twig
{{ var is null }}
.. note::
``none`` is an alias for ``null``.
php-twig-2.12.5/doc/tests/odd.rst 0000664 0000000 0000000 00000000233 13624573447 0016564 0 ustar 00root root 0000000 0000000 ``odd``
=======
``odd`` returns ``true`` if the given number is odd:
.. code-block:: twig
{{ var is odd }}
.. seealso:: :doc:`even<../tests/even>`
php-twig-2.12.5/doc/tests/sameas.rst 0000664 0000000 0000000 00000000417 13624573447 0017273 0 ustar 00root root 0000000 0000000 ``same as``
===========
``same as`` checks if a variable is the same as another variable.
This is equivalent to ``===`` in PHP:
.. code-block:: twig
{% if foo.attribute is same as(false) %}
the foo attribute really is the 'false' PHP value
{% endif %}
php-twig-2.12.5/drupal_test.sh 0000775 0000000 0000000 00000003321 13624573447 0016243 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -x
set -e
REPO=`pwd`
cd /tmp
rm -rf drupal-twig-test
composer create-project --no-interaction drupal-composer/drupal-project:8.x-dev drupal-twig-test
cd drupal-twig-test
(cd vendor/twig && rm -rf twig && ln -sf $REPO twig)
echo '$config["system.logging"]["error_level"] = "verbose";' >> web/sites/default/settings.php
composer require drupal/core:8.7.x-dev webflo/drupal-core-require-dev:8.7.x-dev "egulias/email-validator:^2.0"
php ./web/core/scripts/drupal install --no-interaction demo_umami > output
perl -p -i -e 's/^([A-Za-z]+)\: (.+)$/export DRUPAL_\1=\2/' output
source output
wget https://get.symfony.com/cli/installer -O - | bash
export PATH="$HOME/.symfony/bin:$PATH"
symfony server:start -d --no-tls
curl -OLsS https://get.blackfire.io/blackfire-player.phar
chmod +x blackfire-player.phar
cat > drupal-tests.bkf <