.editorconfig 0000664 0000000 0000000 00000000340 13233677763 0013551 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
.gitignore 0000664 0000000 0000000 00000000105 13233677763 0013063 0 ustar 00root root 0000000 0000000 /build
/composer.lock
/ext/twig/autom4te.cache/
/phpunit.xml
/vendor
.travis.yml 0000664 0000000 0000000 00000002120 13233677763 0013203 0 ustar 00root root 0000000 0000000 language: php
sudo: false
cache:
directories:
- vendor
- $HOME/.composer/cache/files
php:
- 5.2
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
- hhvm
env:
- TWIG_EXT=no
- TWIG_EXT=yes
before_install:
- if [[ ! $TRAVIS_PHP_VERSION = hhvm* ]]; then phpenv config-rm xdebug.ini || echo "xdebug not available"; fi
install:
# Composer is not available on PHP 5.2
- if [ ${TRAVIS_PHP_VERSION:0:3} != "5.2" ]; then travis_retry composer install; fi
before_script:
- if [ "$TWIG_EXT" == "yes" ]; then sh -c "cd ext/twig && phpize && ./configure --enable-twig && make && make install"; fi
- if [ "$TWIG_EXT" == "yes" ]; then echo "extension=twig.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`; fi
- if [ ${TRAVIS_PHP_VERSION:0:3} == "5.2" ]; then sed -i.bak "s|vendor/autoload.php|test/bootstrap.php|" phpunit.xml.dist; fi
matrix:
fast_finish: true
exclude:
- php: hhvm
env: TWIG_EXT=yes
- php: 7.0
env: TWIG_EXT=yes
- php: 7.1
env: TWIG_EXT=yes
CHANGELOG 0000664 0000000 0000000 00000121044 13233677763 0012313 0 ustar 00root root 0000000 0000000 * 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
LICENSE 0000664 0000000 0000000 00000002731 13233677763 0012107 0 ustar 00root root 0000000 0000000 Copyright (c) 2009-2016 by the Twig Team.
Some rights reserved.
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.
README.rst 0000664 0000000 0000000 00000000746 13233677763 0012575 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.
More Information
----------------
Read the `documentation`_ for more information.
.. _documentation: http://twig.sensiolabs.org/documentation
composer.json 0000664 0000000 0000000 00000002251 13233677763 0013621 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": "http://twig.sensiolabs.org",
"license": "BSD-3-Clause",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Twig Team",
"homepage": "http://twig.sensiolabs.org/contributors",
"role": "Contributors"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com",
"role": "Project Founder"
}
],
"support": {
"forum": "https://groups.google.com/forum/#!forum/twig-users"
},
"require": {
"php": ">=5.2.7"
},
"require-dev": {
"symfony/phpunit-bridge": "~2.7",
"symfony/debug": "~2.7"
},
"autoload": {
"psr-0" : {
"Twig_" : "lib/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.28-dev"
}
}
}
doc/ 0000775 0000000 0000000 00000000000 13233677763 0011644 5 ustar 00root root 0000000 0000000 doc/advanced.rst 0000664 0000000 0000000 00000072024 13233677763 0014150 0 ustar 00root root 0000000 0000000 Extending Twig
==============
.. caution::
This section describes how to extend Twig as of **Twig 1.12**. If you are
using an older version, read the :doc:`legacy` chapter
instead.
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 easily. 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:: jinja
{% 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:: jinja
{{ '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 of Twig.
Now, let's use a ``lipsum`` *filter*:
.. code-block:: jinja
{{ 40|lipsum }}
Again, it works, but it looks weird. A filter transforms the passed value to
something else but 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:: jinja
{{ 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:: jinja
{{ 'some text' ~ lipsum(40) ~ 'some more text' }}
{% set lipsum = lipsum(40) %}
Last but not the least, you can also use a *global* object with a method able
to generate lorem ipsum text:
.. code-block:: jinja
{{ 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* trivial frequent Content generation
*global* trivial frequent Helper object
*function* trivial frequent Content generation
*filter* trivial frequent Value transformation
*tag* complex rare DSL language construct
*test* trivial rare Boolean decision
*operator* trivial 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:: jinja
{{ text.lipsum(40) }}
Filters
-------
Creating a filter is as simple as associating a name with a PHP callable::
// an anonymous function
$filter = new Twig_SimpleFilter('rot13', function ($string) {
return str_rot13($string);
});
// or a simple PHP function
$filter = new Twig_SimpleFilter('rot13', 'str_rot13');
// or a class static method
$filter = new Twig_SimpleFilter('rot13', array('SomeClass', 'rot13Filter'));
$filter = new Twig_SimpleFilter('rot13', 'SomeClass::rot13Filter');
// or a class method
$filter = new Twig_SimpleFilter('rot13', array($this, 'rot13Filter'));
// the one below needs a runtime implementation (see below for more information)
$filter = new Twig_SimpleFilter('rot13', array('SomeClass', 'rot13Filter'));
The first argument passed to the ``Twig_SimpleFilter`` 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 your Twig environment::
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
And here is how to use it in a template:
.. code-block:: jinja
{{ '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:: jinja
{{ 'TWIG'|lower }}
{{ now|date('d/m/Y') }}
is compiled to something like the following::
The ``Twig_SimpleFilter`` class takes an array of options as its last
argument::
$filter = new Twig_SimpleFilter('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_SimpleFilter('rot13', function (Twig_Environment $env, $string) {
// get the current charset for instance
$charset = $env->getCharset();
return str_rot13($string);
}, array('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_SimpleFilter('rot13', function ($context, $string) {
// ...
}, array('needs_context' => true));
$filter = new Twig_SimpleFilter('rot13', function (Twig_Environment $env, $context, $string) {
// ...
}, array('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_SimpleFilter('nl2br', 'nl2br', array('is_safe' => array('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_SimpleFilter('somefilter', 'somefilter', array('pre_escape' => 'html', 'is_safe' => array('html')));
Variadic Filters
~~~~~~~~~~~~~~~~
.. versionadded:: 1.19
Support for variadic filters was added in Twig 1.19.
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_SimpleFilter('thumbnail', function ($file, array $options = array()) {
// ...
}, array('is_variadic' => true));
Be warned that 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 as
the ``*`` can be any string::
$filter = new Twig_SimpleFilter('*_path', function ($name, $arguments) {
// ...
});
The following filters will be matched by the above defined dynamic filter:
* ``product_path``
* ``category_path``
A dynamic filter can define more than one dynamic parts::
$filter = new Twig_SimpleFilter('*_path_*', function ($name, $suffix, $arguments) {
// ...
});
The filter will receive 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
~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.21
Support for deprecated filters was added in Twig 1.21.
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_SimpleFilter('obsolete', function () {
// ...
}, array('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_SimpleFunction``::
$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('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_SimpleTest``::
$twig = new Twig_Environment($loader);
$test = new Twig_SimpleTest('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_SimpleTest('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 should 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_SimpleTest(
'odd',
null,
array('node_class' => 'Twig_Node_Expression_Test_Odd'));
$twig->addTest($test);
class Twig_Node_Expression_Test_Odd extends Twig_Node_Expression_Test
{
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:: jinja
{% 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.
If you want to pass a variable number of positional or named arguments to the
test, set the ``is_variadic`` option to ``true``. Tests also support dynamic
name feature as filters and functions.
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.
Let's create a simple ``set`` tag that allows the definition of simple
variables from within a template. The tag can be used like follows:
.. code-block:: jinja
{% 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 (cf. the template designers chapter for
more information).
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
~~~~~~~~~~~~~~~~~~~~~
Adding a tag is as simple as 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
{
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`` 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 a 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 rather simple::
class Project_Set_Node extends Twig_Node
{
public function __construct($name, Twig_Node_Expression $value, $line, $tag = null)
{
parent::__construct(array('value' => $value), array('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_For`` 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_Block`` for a
usage example).
* ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` 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, global variables, 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).
.. note::
Before writing your own extensions, have a look at the Twig official
extension repository: http://github.com/twigphp/Twig-extensions.
An extension is a class that implements the following interface::
interface Twig_ExtensionInterface
{
/**
* Initializes the runtime environment.
*
* This is where you can load some file that contains filter functions for instance.
*
* @deprecated since 1.23 (to be removed in 2.0), implement Twig_Extension_InitRuntimeInterface instead
*/
function initRuntime(Twig_Environment $environment);
/**
* Returns the token parser instances to add to the existing list.
*
* @return (Twig_TokenParserInterface|Twig_TokenParserBrokerInterface)[]
*/
function getTokenParsers();
/**
* Returns the node visitor instances to add to the existing list.
*
* @return Twig_NodeVisitorInterface[]
*/
function getNodeVisitors();
/**
* Returns a list of filters to add to the existing list.
*
* @return Twig_SimpleFilter[]
*/
function getFilters();
/**
* Returns a list of tests to add to the existing list.
*
* @return Twig_SimpleTest[]
*/
function getTests();
/**
* Returns a list of functions to add to the existing list.
*
* @return Twig_SimpleFunction[]
*/
function getFunctions();
/**
* Returns a list of operators to add to the existing list.
*
* @return array An array of operators
*/
function getOperators();
/**
* Returns a list of global variables to add to the existing list.
*
* @return array An array of global variables
*
* @deprecated since 1.23 (to be removed in 2.0), implement Twig_Extension_GlobalsInterface instead
*/
function getGlobals();
/**
* Returns the name of the extension.
*
* @return string The extension name
*
* @deprecated since 1.26 (to be removed in 2.0), not used anymore internally
*/
function getName();
}
To keep your extension class clean and lean, inherit from the built-in
``Twig_Extension`` class instead of implementing the interface as it provides
empty implementations for all methods:
class Project_Twig_Extension extends Twig_Extension
{
}
Of course, this extension does nothing for now. We will customize it in the
next sections.
.. note::
Prior to Twig 1.26, you must implement the ``getName()`` method which must
return a unique identifier for the extension.
Twig does not care where you save your extension 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 implements Twig_Extension_GlobalsInterface
{
public function getGlobals()
{
return array(
'text' => new Text(),
);
}
// ...
}
Functions
~~~~~~~~~
Functions can be registered in an extension via the ``getFunctions()``
method::
class Project_Twig_Extension extends Twig_Extension
{
public function getFunctions()
{
return array(
new Twig_SimpleFunction('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
{
public function getFilters()
{
return array(
new Twig_SimpleFilter('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
{
public function getTokenParsers()
{
return array(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
``!``, ``||``, and ``&&`` operators::
class Project_Twig_Extension extends Twig_Extension
{
public function getOperators()
{
return array(
array(
'!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
),
array(
'||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
'&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
),
);
}
// ...
}
Tests
~~~~~
The ``getTests()`` method lets you add new test functions::
class Project_Twig_Extension extends Twig_Extension
{
public function getTests()
{
return array(
new Twig_SimpleTest('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
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function getFunctions()
{
return array(
new Twig_SimpleFunction('rot13', array($this, 'rot13')),
);
}
public function rot13($value)
{
return $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).
As of Twig 1.26, you can easily decouple the extension definitions from their
runtime implementations by registering a ``Twig_RuntimeLoaderInterface``
instance on the environment that knows how to instantiate such runtime classes
(runtime classes must be autoload-able)::
class RuntimeLoader implements Twig_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());
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 extends Twig_Extension
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function rot13($value)
{
return $rot13Provider->rot13($value);
}
}
class Project_Twig_Extension extends Twig_Extension
{
public function getFunctions()
{
return array(
new Twig_SimpleFunction('rot13', array('Project_Twig_RuntimeExtension', 'rot13')),
// or
new Twig_SimpleFunction('rot13', 'Project_Twig_RuntimeExtension::rot13'),
);
}
}
Overloading
-----------
To overload an already defined filter, test, operator, global variable, or
function, re-define it in an extension and register it **as late as
possible** (order matters)::
class MyCoreExtension extends Twig_Extension
{
public function getFilters()
{
return array(
new Twig_SimpleFilter('date', array($this, 'dateFilter')),
);
}
public function dateFilter($timestamp, $format = 'F j, Y H:i')
{
// do something different from the built-in date filter
}
}
$twig = new Twig_Environment($loader);
$twig->addExtension(new MyCoreExtension());
Here, we have overloaded the built-in ``date`` filter with a custom one.
If you do the same on the ``Twig_Environment`` itself, beware that it takes
precedence over any other registered extensions::
$twig = new Twig_Environment($loader);
$twig->addFilter(new Twig_SimpleFilter('date', function ($timestamp, $format = 'F j, Y H:i') {
// do something different from the built-in date filter
}));
// the date filter will come from the above registration, not
// from the registered extension below
$twig->addExtension(new MyCoreExtension());
.. caution::
Note that overloading the built-in Twig elements is not recommended as it
might be confusing.
Testing an Extension
--------------------
Functional Tests
~~~~~~~~~~~~~~~~
You can create functional tests for extensions simply 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 array(
new Project_Twig_Extension1(),
new Project_Twig_Extension2(),
);
}
public function getFixturesDir()
{
return dirname(__FILE__).'/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`: http://www.php.net/manual/en/function.str-rot13.php
.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures
.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node
doc/advanced_legacy.rst 0000664 0000000 0000000 00000064554 13233677763 0015505 0 ustar 00root root 0000000 0000000 Extending Twig
==============
.. caution::
This section describes how to extends Twig for versions **older than
1.12**. If you are using a newer version, read the :doc:`newer`
chapter instead.
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 easily. 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 by calling methods on the Twig environment instance,
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:: jinja
{% 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:: jinja
{{ '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 of Twig.
Now, let's use a ``lipsum`` *filter*:
.. code-block:: jinja
{{ 40|lipsum }}
Again, it works, but it looks weird. A filter transforms the passed value to
something else but 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:: jinja
{{ 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:: jinja
{{ 'some text' ~ ipsum(40) ~ 'some more text' }}
{% set ipsum = ipsum(40) %}
Last but not the least, you can also use a *global* object with a method able
to generate lorem ipsum text:
.. code-block:: jinja
{{ 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* trivial frequent Content generation
*global* trivial frequent Helper object
*function* trivial frequent Content generation
*filter* trivial frequent Value transformation
*tag* complex rare DSL language construct
*test* trivial rare Boolean decision
*operator* trivial 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:: jinja
{{ text.lipsum(40) }}
Filters
-------
A filter is a regular PHP function or an object method that takes the left
side of the filter (before the pipe ``|``) as first argument and the extra
arguments passed to the filter (within parentheses ``()``) as extra arguments.
Defining a filter is as easy as associating the filter name with a PHP
callable. For instance, let's say you have the following code in a template:
.. code-block:: jinja
{{ 'TWIG'|lower }}
When compiling this template to PHP, Twig looks for the PHP callable
associated with the ``lower`` filter. The ``lower`` filter is a built-in Twig
filter, and it is simply mapped to the PHP ``strtolower()`` function. After
compilation, the generated PHP code is roughly equivalent to:
.. code-block:: html+php
As you can see, the ``'TWIG'`` string is passed as a first argument to the PHP
function.
A filter can also take extra arguments like in the following example:
.. code-block:: jinja
{{ now|date('d/m/Y') }}
In this case, the extra arguments are passed to the function after the main
argument, and the compiled code is equivalent to:
.. code-block:: html+php
Let's see how to create a new filter.
In this section, we will create a ``rot13`` filter, which should return the
`rot13`_ transformation of a string. Here is an example of its usage and the
expected output:
.. code-block:: jinja
{{ "Twig"|rot13 }}
{# should displays Gjvt #}
Adding a filter is as simple as calling the ``addFilter()`` method on the
``Twig_Environment`` instance::
$twig = new Twig_Environment($loader);
$twig->addFilter('rot13', new Twig_Filter_Function('str_rot13'));
The second argument of ``addFilter()`` is an instance of ``Twig_Filter``.
Here, we use ``Twig_Filter_Function`` as the filter is a PHP function. The
first argument passed to the ``Twig_Filter_Function`` constructor is the name
of the PHP function to call, here ``str_rot13``, a native PHP function.
Let's say I now want to be able to add a prefix before the converted string:
.. code-block:: jinja
{{ "Twig"|rot13('prefix_') }}
{# should displays prefix_Gjvt #}
As the PHP ``str_rot13()`` function does not support this requirement, let's
create a new PHP function::
function project_compute_rot13($string, $prefix = '')
{
return $prefix.str_rot13($string);
}
As you can see, the ``prefix`` argument of the filter is passed as an extra
argument to the ``project_compute_rot13()`` function.
Adding this filter is as easy as before::
$twig->addFilter('rot13', new Twig_Filter_Function('project_compute_rot13'));
For better encapsulation, a filter can also be defined as a static method of a
class. The ``Twig_Filter_Function`` class can also be used to register such
static methods as filters::
$twig->addFilter('rot13', new Twig_Filter_Function('SomeClass::rot13Filter'));
.. tip::
In an extension, you can also define a filter as a static method of the
extension class.
Environment aware Filters
~~~~~~~~~~~~~~~~~~~~~~~~~
The ``Twig_Filter`` classes take options as their last argument. For instance,
if you want access to the current environment instance in your filter, set the
``needs_environment`` option to ``true``::
$filter = new Twig_Filter_Function('str_rot13', array('needs_environment' => true));
Twig will then pass the current environment as the first argument to the
filter call::
function twig_compute_rot13(Twig_Environment $env, $string)
{
// get the current charset for instance
$charset = $env->getCharset();
return str_rot13($string);
}
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_Filter_Function('nl2br', array('is_safe' => array('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_Filter_Function('somefilter', array('pre_escape' => 'html', 'is_safe' => array('html')));
Dynamic Filters
~~~~~~~~~~~~~~~
.. versionadded:: 1.5
Dynamic filters support was added in Twig 1.5.
A filter name containing the special ``*`` character is a dynamic filter as
the ``*`` can be any string::
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
function twig_path($name, $arguments)
{
// ...
}
The following filters will be matched by the above defined dynamic filter:
* ``product_path``
* ``category_path``
A dynamic filter can define more than one dynamic parts::
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
function twig_path($name, $suffix, $arguments)
{
// ...
}
The filter will receive all dynamic part values before the normal filters
arguments. For instance, a call to ``'foo'|a_path_b()`` will result in the
following PHP call: ``twig_path('a', 'b', 'foo')``.
Functions
---------
A function is a regular PHP function or an object method that can be called from
templates.
.. code-block:: jinja
{{ constant("DATE_W3C") }}
When compiling this template to PHP, Twig looks for the PHP callable
associated with the ``constant`` function. The ``constant`` function is a built-in Twig
function, and it is simply mapped to the PHP ``constant()`` function. After
compilation, the generated PHP code is roughly equivalent to:
.. code-block:: html+php
Adding a function is similar to adding a filter. This can be done by calling the
``addFunction()`` method on the ``Twig_Environment`` instance::
$twig = new Twig_Environment($loader);
$twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
You can also expose extension methods as functions in your templates::
// $this is an object that implements Twig_ExtensionInterface.
$twig = new Twig_Environment($loader);
$twig->addFunction('otherFunction', new Twig_Function_Method($this, 'someMethod'));
Functions also support ``needs_environment`` and ``is_safe`` parameters.
Dynamic Functions
~~~~~~~~~~~~~~~~~
.. versionadded:: 1.5
Dynamic functions support was added in Twig 1.5.
A function name containing the special ``*`` character is a dynamic function
as the ``*`` can be any string::
$twig->addFunction('*_path', new Twig_Function_Function('twig_path'));
function twig_path($name, $arguments)
{
// ...
}
The following functions will be matched by the above defined dynamic function:
* ``product_path``
* ``category_path``
A dynamic function can define more than one dynamic parts::
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
function twig_path($name, $suffix, $arguments)
{
// ...
}
The function will receive all dynamic part values before the normal functions
arguments. For instance, a call to ``a_path_b('foo')`` will result in the
following PHP call: ``twig_path('a', 'b', 'foo')``.
Tags
----
One of the most exciting feature 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.
Let's create a simple ``set`` tag that allows the definition of simple
variables from within a template. The tag can be used like follows:
.. code-block:: jinja
{% 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 (cf. the template designers chapter for
more information).
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
~~~~~~~~~~~~~~~~~~~~~
Adding a tag is as simple as 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
{
public function parse(Twig_Token $token)
{
$lineno = $token->getLine();
$name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
$this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, '=');
$value = $this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
return new Project_Set_Node($name, $value, $lineno, $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`` 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 a 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 rather simple::
class Project_Set_Node extends Twig_Node
{
public function __construct($name, Twig_Node_Expression $value, $lineno, $tag = null)
{
parent::__construct(array('value' => $value), array('name' => $name), $lineno, $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_For`` 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_Block`` for a
usage example).
* ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` 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, global variables, functions, and node
visitors.
Creating an extension also makes for a better separation of code that is
executed at compilation time and code needed at runtime. As such, it makes
your code faster.
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 the
``auto_reload`` is enabled).
.. note::
Before writing your own extensions, have a look at the Twig official
extension repository: http://github.com/twigphp/Twig-extensions.
An extension is a class that implements the following interface::
interface Twig_ExtensionInterface
{
/**
* Initializes the runtime environment.
*
* This is where you can load some file that contains filter functions for instance.
*/
function initRuntime(Twig_Environment $environment);
/**
* Returns the token parser instances to add to the existing list.
*
* @return (Twig_TokenParserInterface|Twig_TokenParserBrokerInterface)[]
*/
function getTokenParsers();
/**
* Returns the node visitor instances to add to the existing list.
*
* @return Twig_NodeVisitorInterface[]
*/
function getNodeVisitors();
/**
* Returns a list of filters to add to the existing list.
*
* @return Twig_SimpleFilter[]
*/
function getFilters();
/**
* Returns a list of tests to add to the existing list.
*
* @return Twig_SimpleTest[]
*/
function getTests();
/**
* Returns a list of functions to add to the existing list.
*
* @return Twig_SimpleFunction[]
*/
function getFunctions();
/**
* Returns a list of operators to add to the existing list.
*
* @return array An array of operators
*/
function getOperators();
/**
* Returns a list of global variables to add to the existing list.
*
* @return array An array of global variables
*/
function getGlobals();
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
function getName();
}
To keep your extension class clean and lean, it can inherit from the built-in
``Twig_Extension`` class instead of implementing the whole interface. That
way, you just need to implement the ``getName()`` method as the
``Twig_Extension`` provides empty implementations for all other methods.
The ``getName()`` method must return a unique identifier for your extension.
Now, with this information in mind, let's create the most basic extension
possible::
class Project_Twig_Extension extends Twig_Extension
{
public function getName()
{
return 'project';
}
}
.. note::
Of course, this extension does nothing for now. We will customize it in
the next sections.
Twig does not care where you save your extension 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());
Of course, you need to first load the extension file by either using
``require_once()`` or by using an autoloader (see `spl_autoload_register()`_).
.. tip::
The bundled 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
{
public function getGlobals()
{
return array(
'text' => new Text(),
);
}
// ...
}
Functions
~~~~~~~~~
Functions can be registered in an extension via the ``getFunctions()``
method::
class Project_Twig_Extension extends Twig_Extension
{
public function getFunctions()
{
return array(
'lipsum' => new Twig_Function_Function('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
{
public function getFilters()
{
return array(
'rot13' => new Twig_Filter_Function('str_rot13'),
);
}
// ...
}
As you can see in the above code, the ``getFilters()`` method returns an array
where keys are the name of the filters (``rot13``) and the values the
definition of the filter (``new Twig_Filter_Function('str_rot13')``).
As seen in the previous chapter, you can also define filters as static methods
on the extension class::
$twig->addFilter('rot13', new Twig_Filter_Function('Project_Twig_Extension::rot13Filter'));
You can also use ``Twig_Filter_Method`` instead of ``Twig_Filter_Function``
when defining a filter to use a method::
class Project_Twig_Extension extends Twig_Extension
{
public function getFilters()
{
return array(
'rot13' => new Twig_Filter_Method($this, 'rot13Filter'),
);
}
public function rot13Filter($string)
{
return str_rot13($string);
}
// ...
}
The first argument of the ``Twig_Filter_Method`` constructor is always
``$this``, the current extension object. The second one is the name of the
method to call.
Using methods for filters is a great way to package your filter without
polluting the global namespace. This also gives the developer more flexibility
at the cost of a small overhead.
Overriding default Filters
..........................
If some default core filters do not suit your needs, you can easily override
them by creating your own extension. Just use the same names as the one you
want to override::
class MyCoreExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'date' => new Twig_Filter_Method($this, 'dateFilter'),
// ...
);
}
public function dateFilter($timestamp, $format = 'F j, Y H:i')
{
return '...'.twig_date_format_filter($timestamp, $format);
}
public function getName()
{
return 'project';
}
}
Here, we override the ``date`` filter with a custom one. Using this extension
is as simple as registering the ``MyCoreExtension`` extension by calling the
``addExtension()`` method on the environment instance::
$twig = new Twig_Environment($loader);
$twig->addExtension(new MyCoreExtension());
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
{
public function getTokenParsers()
{
return array(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 allows to add new operators. Here is how to add
``!``, ``||``, and ``&&`` operators::
class Project_Twig_Extension extends Twig_Extension
{
public function getOperators()
{
return array(
array(
'!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
),
array(
'||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
'&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
),
);
}
// ...
}
Tests
~~~~~
The ``getTests()`` methods allows to add new test functions::
class Project_Twig_Extension extends Twig_Extension
{
public function getTests()
{
return array(
'even' => new Twig_Test_Function('twig_test_even'),
);
}
// ...
}
Testing an Extension
--------------------
.. versionadded:: 1.10
Support for functional tests was added in Twig 1.10.
Functional Tests
~~~~~~~~~~~~~~~~
You can create functional tests for extensions simply 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 array(
new Project_Twig_Extension1(),
new Project_Twig_Extension2(),
);
}
public function getFixturesDir()
{
return dirname(__FILE__).'/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.
.. _`spl_autoload_register()`: http://www.php.net/spl_autoload_register
.. _`rot13`: http://www.php.net/manual/en/function.str-rot13.php
.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures
.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node
doc/api.rst 0000664 0000000 0000000 00000046740 13233677763 0013162 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 from the file
system or other locations.
Most applications will create one ``Twig_Environment`` object on application
initialization and use that to load templates. In some cases it's however
useful to have multiple environments side by side, if different configurations
are in use.
The simplest way to configure Twig to load templates for your application
looks roughly like this::
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
This will create a template environment with the default settings and a loader
that looks up the templates in the ``/path/to/templates/`` folder. 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');
.. note::
Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a
``Twig_Template`` instance.
To render the template with some variables, call the ``render()`` method::
echo $template->render(array('the' => 'variables', 'go' => 'here'));
.. note::
The ``display()`` method is a shortcut to output the template directly.
You can also load and render the template in one fell swoop::
echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));
.. versionadded:: 1.28
The possibility to render blocks from the API was added in Twig 1.28.
If a template defines blocks, they can be rendered individually via the
``renderBlock()`` call::
echo $template->renderBlock('block_name', array('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, array('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* or *boolean*
If set to ``true``, HTML auto-escaping will be enabled by
default for all templates (default to ``true``).
As of Twig 1.8, you can set the escaping strategy to use (``html``, ``js``,
``false`` to disable).
As of Twig 1.9, you can set the escaping strategy to use (``css``, ``url``,
``html_attr``, or a PHP callback that takes the template name and must
return the escaping strategy to use -- the callback cannot be a function name
to avoid collision with built-in escaping strategies).
As of Twig 1.17, the ``filename`` escaping strategy (renamed to ``name`` as
of Twig 1.27) 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 APC.
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 provides:
``Twig_Loader_Filesystem``
..........................
.. versionadded:: 1.10
The ``prependPath()`` and support for namespaces were added in Twig 1.10.
.. versionadded:: 1.27
Relative paths support was added in Twig 1.27.
``Twig_Loader_Filesystem`` 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_Filesystem($templateDir);
It can also look for templates in an array of directories::
$loader = new Twig_Loader_Filesystem(array($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', array());
``Twig_Loader_Filesystem`` 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_Filesystem('templates', getcwd().'/..');
.. note::
When not passing the root path as a second argument, Twig uses ``getcwd()``
for relative paths.
``Twig_Loader_Array``
.....................
``Twig_Loader_Array`` loads a template from a PHP array. It's passed an array
of strings bound to template names::
$loader = new Twig_Loader_Array(array(
'index.html' => 'Hello {{ name }}!',
));
$twig = new Twig_Environment($loader);
echo $twig->render('index.html', array('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`` or ``String`` loaders 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_Chain``
.....................
``Twig_Loader_Chain`` delegates the loading of templates to other loaders::
$loader1 = new Twig_Loader_Array(array(
'base.html' => '{% block content %}{% endblock %}',
));
$loader2 = new Twig_Loader_Array(array(
'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
'base.html' => 'Will never be loaded',
));
$loader = new Twig_Loader_Chain(array($loader1, $loader2));
$twig = new Twig_Environment($loader);
When looking for a template, Twig will try each loader in turn and it will
return 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``.
``Twig_Loader_Chain`` accepts any loader that implements
``Twig_LoaderInterface``.
.. note::
You can also add loaders via the ``addLoader()`` method.
Create your own Loader
~~~~~~~~~~~~~~~~~~~~~~
All loaders implement the ``Twig_LoaderInterface``::
interface Twig_LoaderInterface
{
/**
* Gets the source code of a template, given its name.
*
* @param string $name string The name of the template to load
*
* @return string The template source code
*
* @deprecated since 1.27 (to be removed in 2.0), implement Twig_SourceContextLoaderInterface
*/
function getSource($name);
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param string $name string The name of the template to load
*
* @return string The cache key
*/
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
*/
function isFresh($name, $time);
}
The ``isFresh()`` method must return ``true`` if the current cached template
is still fresh, given the last modification time, or ``false`` otherwise.
.. note::
As of Twig 1.27, you should also implement
``Twig_SourceContextLoaderInterface`` to avoid deprecation notices.
.. tip::
As of Twig 1.11.0, you can also implement ``Twig_ExistsLoaderInterface``
to make your loader faster when used with the chain loader.
Using Extensions
----------------
Twig extensions are packages that add new features to Twig. Using an
extension is as simple as using the ``addExtension()`` method::
$twig->addExtension(new Twig_Extension_Sandbox());
Twig comes bundled with the following extensions:
* *Twig_Extension_Core*: Defines all the core features of Twig.
* *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
to escape/unescape blocks of code.
* *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
environment, making it safe to evaluate untrusted code.
* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig
1.18).
* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
The core, escaper, and optimizer extensions do not need to be added to the
Twig environment, as they are registered by default.
Built-in Extensions
-------------------
This section describes the features added by the built-in extensions.
.. tip::
Read the chapter about 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_Escaper('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:: jinja
{{ article.to_html|raw }}
You can also change the escaping mode locally by using the ``autoescape`` tag
(see the :doc:`autoescape` doc for the syntax used before
Twig 1.8):
.. code-block:: jinja
{% 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:: jinja
{{ "Twig" }} {# won't be escaped #}
{% set text = "Twig" %}
{{ text }} {# will be escaped #}
* Expressions which the result is always a literal or a variable marked safe
are never automatically escaped:
.. code-block:: jinja
{{ foo ? "Twig" : "Twig" }} {# won't be escaped #}
{% set text = "Twig" %}
{{ foo ? text : "Twig" }} {# will be escaped #}
{% set text = "Twig" %}
{{ foo ? text|raw : "Twig" }} {# won't be escaped #}
{% set text = "Twig" %}
{{ foo ? text|escape : "Twig" }} {# the result of the expression won't be escaped #}
* Escaping is applied before printing, after any other filter is applied:
.. code-block:: jinja
{{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
* The `raw` filter should only be used at the end of the filter chain:
.. code-block:: jinja
{{ 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:: jinja
{% 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 = array('if');
$filters = array('upper');
$methods = array(
'Article' => array('getTitle', 'getBody'),
);
$properties = array(
'Article' => array('title', 'body'),
);
$functions = array('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_Sandbox($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:: jinja
{% 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_Sandbox($policy, true);
Profiler Extension
~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.18
The Profile extension was added in Twig 1.18.
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_Profiler($profile));
$dumper = new Twig_Profiler_Dumper_Text();
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_Blackfire();
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_Optimizer());
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_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
$twig->addExtension($optimizer);
Twig supports the following optimizations:
* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL``, enables all optimizations
(this is the default value).
* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_NONE``, disables all optimizations.
This reduces the compilation time, but it can increase the execution time
and the consumed memory.
* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR``, optimizes the ``for`` tag by
removing the ``loop`` variable creation whenever possible.
* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER``, removes the ``raw``
filter whenever possible.
* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS``, simplifies the creation
and access of variables in the compiled templates whenever possible.
Exceptions
----------
Twig can throw exceptions:
* ``Twig_Error``: The base exception for all errors.
* ``Twig_Error_Syntax``: Thrown to tell the user that there is a problem with
the template syntax.
* ``Twig_Error_Runtime``: Thrown when an error occurs at runtime (when a filter
does not exist for instance).
* ``Twig_Error_Loader``: 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.
doc/coding_standards.rst 0000664 0000000 0000000 00000004521 13233677763 0015706 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:: jinja
{{ foo }}
{# comment #}
{% if foo %}{% endif %}
When using the whitespace control character, do not put any spaces between
it and the delimiter:
.. code-block:: jinja
{{- 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:: jinja
{{ 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:: jinja
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
* Do not put any spaces after an opening parenthesis and before a closing
parenthesis in expressions:
.. code-block:: jinja
{{ 1 + (2 * 3) }}
* Do not put any spaces before and after string delimiters:
.. code-block:: jinja
{{ 'foo' }}
{{ "foo" }}
* Do not put any spaces before and after the following operators: ``|``,
``.``, ``..``, ``[]``:
.. code-block:: jinja
{{ 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:: jinja
{{ 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:: jinja
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
* Use lower cased and underscored variable names:
.. code-block:: jinja
{% 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:: jinja
{% block foo %}
{% if true %}
true
{% endif %}
{% endblock %}
doc/deprecated.rst 0000664 0000000 0000000 00000016370 13233677763 0014505 0 ustar 00root root 0000000 0000000 Deprecated Features
===================
This document lists all deprecated features in Twig. Deprecated features are
kept for backward compatibility and removed in the next major release (a
feature that was deprecated in Twig 1.x is removed in Twig 2.0).
Deprecation Notices
-------------------
As of Twig 1.21, Twig generates deprecation notices when a template uses
deprecated features. See :ref:`deprecation-notices` for more information.
Token Parsers
-------------
* As of Twig 1.x, the token parser broker sub-system is deprecated. The
following class and interface will be removed in 2.0:
* ``Twig_TokenParserBrokerInterface``
* ``Twig_TokenParserBroker``
* As of Twig 1.27, ``Twig_Parser::getFilename()`` is deprecated. From a token
parser, use ``$this->parser->getStream()->getSourceContext()->getPath()`` instead.
* As of Twig 1.27, ``Twig_Parser::getEnvironment()`` is deprecated.
Extensions
----------
* As of Twig 1.x, the ability to remove an extension is deprecated and the
``Twig_Environment::removeExtension()`` method will be removed in 2.0.
* As of Twig 1.23, the ``Twig_ExtensionInterface::initRuntime()`` method is
deprecated. You have two options to avoid the deprecation notice: if you
implement this method to store the environment for your custom filters,
functions, or tests, use the ``needs_environment`` option instead; if you
have more complex needs, explicitly implement
``Twig_Extension_InitRuntimeInterface`` (not recommended).
* As of Twig 1.23, the ``Twig_ExtensionInterface::getGlobals()`` method is
deprecated. Implement ``Twig_Extension_GlobalsInterface`` to avoid
deprecation notices.
* As of Twig 1.26, the ``Twig_ExtensionInterface::getName()`` method is
deprecated and it is not used internally anymore.
PEAR
----
PEAR support has been discontinued in Twig 1.15.1, and no PEAR packages are
provided anymore. Use Composer instead.
Filters
-------
* As of Twig 1.x, use ``Twig_SimpleFilter`` to add a filter. The following
classes and interfaces will be removed in 2.0:
* ``Twig_FilterInterface``
* ``Twig_FilterCallableInterface``
* ``Twig_Filter``
* ``Twig_Filter_Function``
* ``Twig_Filter_Method``
* ``Twig_Filter_Node``
* As of Twig 2.x, the ``Twig_SimpleFilter`` class is deprecated and will be
removed in Twig 3.x (use ``Twig_Filter`` instead). In Twig 2.x,
``Twig_SimpleFilter`` is just an alias for ``Twig_Filter``.
Functions
---------
* As of Twig 1.x, use ``Twig_SimpleFunction`` to add a function. The following
classes and interfaces will be removed in 2.0:
* ``Twig_FunctionInterface``
* ``Twig_FunctionCallableInterface``
* ``Twig_Function``
* ``Twig_Function_Function``
* ``Twig_Function_Method``
* ``Twig_Function_Node``
* As of Twig 2.x, the ``Twig_SimpleFunction`` class is deprecated and will be
removed in Twig 3.x (use ``Twig_Function`` instead). In Twig 2.x,
``Twig_SimpleFunction`` is just an alias for ``Twig_Function``.
Tests
-----
* As of Twig 1.x, use ``Twig_SimpleTest`` to add a test. The following classes
and interfaces will be removed in 2.0:
* ``Twig_TestInterface``
* ``Twig_TestCallableInterface``
* ``Twig_Test``
* ``Twig_Test_Function``
* ``Twig_Test_Method``
* ``Twig_Test_Node``
* As of Twig 2.x, the ``Twig_SimpleTest`` class is deprecated and will be
removed in Twig 3.x (use ``Twig_Test`` instead). In Twig 2.x,
``Twig_SimpleTest`` is just an alias for ``Twig_Test``.
* The ``sameas`` and ``divisibleby`` tests are deprecated in favor of ``same
as`` and ``divisible by`` respectively.
Tags
----
* As of Twig 1.x, the ``raw`` tag is deprecated. You should use ``verbatim``
instead.
Nodes
-----
* As of Twig 1.x, ``Node::toXml()`` is deprecated and will be removed in Twig
2.0.
* As of Twig 1.26, ``Node::$nodes`` should only contains ``Twig_Node``
instances, storing a ``null`` value is deprecated and won't be possible in
Twig 2.x.
* As of Twig 1.27, the ``filename`` attribute on ``Twig_Node_Module`` is
deprecated. Use ``getName()`` instead.
* As of Twig 1.27, the ``Twig_Node::getFilename()/Twig_Node::getLine()``
methods are deprecated, use
``Twig_Node::getTemplateName()/Twig_Node::getTemplateLine()`` instead.
Interfaces
----------
* As of Twig 2.x, the following interfaces are deprecated and empty (they will
be removed in Twig 3.0):
* ``Twig_CompilerInterface`` (use ``Twig_Compiler`` instead)
* ``Twig_LexerInterface`` (use ``Twig_Lexer`` instead)
* ``Twig_NodeInterface`` (use ``Twig_Node`` instead)
* ``Twig_ParserInterface`` (use ``Twig_Parser`` instead)
* ``Twig_ExistsLoaderInterface`` (merged with ``Twig_LoaderInterface``)
* ``Twig_SourceContextLoaderInterface`` (merged with ``Twig_LoaderInterface``)
* ``Twig_TemplateInterface`` (use ``Twig_Template`` instead, and use
those constants Twig_Template::ANY_CALL, Twig_Template::ARRAY_CALL,
Twig_Template::METHOD_CALL)
Compiler
--------
* As of Twig 1.26, the ``Twig_Compiler::getFilename()`` has been deprecated.
You should not use it anyway as its values is not reliable.
* As of Twig 1.27, the ``Twig_Compiler::addIndentation()`` has been deprecated.
Use ``Twig_Compiler::write('')`` instead.
Loaders
-------
* As of Twig 1.x, ``Twig_Loader_String`` is deprecated and will be removed in
2.0. You can render a string via ``Twig_Environment::createTemplate()``.
* As of Twig 1.27, ``Twig_LoaderInterface::getSource()`` is deprecated.
Implement ``Twig_SourceContextLoaderInterface`` instead and use
``getSourceContext()``.
Node Visitors
-------------
* Because of the removal of ``Twig_NodeInterface`` in 2.0, you need to extend
``Twig_BaseNodeVisitor`` instead of implementing ``Twig_NodeVisitorInterface``
directly to make your node visitors compatible with both Twig 1.x and 2.x.
Globals
-------
* As of Twig 2.x, the ability to register a global variable after the runtime
or the extensions have been initialized is not possible anymore (but
changing the value of an already registered global is possible).
* As of Twig 1.x, using the ``_self`` global variable to get access to the
current ``Twig_Template`` instance is deprecated; most usages only need the
current template name, which will continue to work in Twig 2.0. In Twig 2.0,
``_self`` returns the current template name instead of the current
``Twig_Template`` instance.
Miscellaneous
-------------
* As of Twig 1.x, ``Twig_Environment::clearTemplateCache()``,
``Twig_Environment::writeCacheFile()``,
``Twig_Environment::clearCacheFiles()``,
``Twig_Environment::getCacheFilename()``,
``Twig_Environment::getTemplateClassPrefix()``,
``Twig_Environment::getLexer()``, ``Twig_Environment::getParser()``, and
``Twig_Environment::getCompiler()`` are deprecated and will be removed in 2.0.
* As of Twig 1.x, ``Twig_Template::getEnvironment()`` and
``Twig_TemplateInterface::getEnvironment()`` are deprecated and will be
removed in 2.0.
* As of Twig 1.27, ``Twig_Error::getTemplateFile()`` and
``Twig_Error::setTemplateFile()`` are deprecated. Use
``Twig_Error::getTemplateName()`` and ``Twig_Error::setTemplateName()``
instead.
* As of Twig 1.27, ``Twig_Template::getSource()`` is deprecated. Use
``Twig_Template::getSourceContext()`` instead.
* As of Twig 1.27, ``Twig_Parser::addHandler()`` and
``Twig_Parser::addNodeVisitor()`` are deprecated and will be removed in 2.0.
doc/filters/ 0000775 0000000 0000000 00000000000 13233677763 0013314 5 ustar 00root root 0000000 0000000 doc/filters/abs.rst 0000664 0000000 0000000 00000000367 13233677763 0014621 0 ustar 00root root 0000000 0000000 ``abs``
=======
The ``abs`` filter returns the absolute value.
.. code-block:: jinja
{# number = -5 #}
{{ number|abs }}
{# outputs 5 #}
.. note::
Internally, Twig uses the PHP `abs`_ function.
.. _`abs`: http://php.net/abs
doc/filters/batch.rst 0000664 0000000 0000000 00000002102 13233677763 0015122 0 ustar 00root root 0000000 0000000 ``batch``
=========
.. versionadded:: 1.12.3
The ``batch`` filter was added in Twig 1.12.3.
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:: jinja
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

Table Of Contents

...
{{ parent() }}
{% endblock %}
The ``parent()`` call will return the content of the ``sidebar`` block as
defined in the ``base.html`` template.
.. seealso:: :doc:`extends`, :doc:`block`, :doc:`block`
doc/functions/random.rst 0000664 0000000 0000000 00000001527 13233677763 0015673 0 ustar 00root root 0000000 0000000 ``random``
==========
.. versionadded:: 1.5
The ``random`` function was added in Twig 1.5.
.. versionadded:: 1.6
String and integer handling was added in Twig 1.6.
The ``random`` function returns a random value depending on the supplied
parameter type:
* a random item from a sequence;
* a random character from a string;
* a random integer between 0 and the integer parameter (inclusive).
.. code-block:: jinja
{{ random(['apple', 'orange', 'citrus']) }} {# example output: orange #}
{{ random('ABC') }} {# example output: C #}
{{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #}
{{ random(5) }} {# example output: 3 #}
Arguments
---------
* ``values``: The values
.. _`mt_rand`: http://php.net/mt_rand
doc/functions/range.rst 0000664 0000000 0000000 00000001611 13233677763 0015501 0 ustar 00root root 0000000 0000000 ``range``
=========
Returns a list containing an arithmetic progression of integers:
.. code-block:: jinja
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
{# outputs 0, 1, 2, 3, #}
When step is given (as the third parameter), it specifies the increment (or
decrement):
.. code-block:: jinja
{% for i in range(0, 6, 2) %}
{{ i }},
{% endfor %}
{# outputs 0, 2, 4, 6, #}
The Twig built-in ``..`` operator is just syntactic sugar for the ``range``
function (with a step of 1):
.. code-block:: jinja
{% for i in 0..3 %}
{{ i }},
{% endfor %}
.. tip::
The ``range`` function works as the native PHP `range`_ function.
Arguments
---------
* ``low``: The first value of the sequence.
* ``high``: The highest possible value of the sequence.
* ``step``: The increment between elements of the sequence.
.. _`range`: http://php.net/range
doc/functions/source.rst 0000664 0000000 0000000 00000001526 13233677763 0015712 0 ustar 00root root 0000000 0000000 ``source``
==========
.. versionadded:: 1.15
The ``source`` function was added in Twig 1.15.
.. versionadded:: 1.18.3
The ``ignore_missing`` flag was added in Twig 1.18.3.
The ``source`` function returns the content of a template without rendering it:
.. code-block:: jinja
{{ source('template.html') }}
{{ source(some_var) }}
When you set the ``ignore_missing`` flag, Twig will return an empty string if
the template does not exist:
.. code-block:: jinja
{{ source('template.html', ignore_missing = true) }}
The function uses the same template loaders as the ones used to include
templates. So, if you are using the filesystem loader, the templates are looked
for in the paths defined by it.
Arguments
---------
* ``name``: The name of the template to read
* ``ignore_missing``: Whether to ignore missing templates or not
doc/functions/template_from_string.rst 0000664 0000000 0000000 00000001675 13233677763 0020643 0 ustar 00root root 0000000 0000000 ``template_from_string``
========================
.. versionadded:: 1.11
The ``template_from_string`` function was added in Twig 1.11.
The ``template_from_string`` function loads a template from a string:
.. code-block:: jinja
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string(page.template)) }}
.. note::
The ``template_from_string`` function is not available by default. You
must add the ``Twig_Extension_StringLoader`` extension explicitly when
creating your Twig environment::
$twig = new Twig_Environment(...);
$twig->addExtension(new Twig_Extension_StringLoader());
.. note::
Even if you will probably always use the ``template_from_string`` function
with the ``include`` function, you can use it with any tag or function that
takes a template as an argument (like the ``embed`` or ``extends`` tags).
Arguments
---------
* ``template``: The template
doc/index.rst 0000664 0000000 0000000 00000000353 13233677763 0013506 0 ustar 00root root 0000000 0000000 Twig
====
.. toctree::
:maxdepth: 2
intro
installation
templates
api
advanced
internals
deprecated
recipes
coding_standards
tags/index
filters/index
functions/index
tests/index
doc/installation.rst 0000664 0000000 0000000 00000006700 13233677763 0015102 0 ustar 00root root 0000000 0000000 Installation
============
You have multiple ways to install Twig.
Installing the Twig PHP package
-------------------------------
Installing via Composer (recommended)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Install `Composer`_ and run the following command to get the latest version:
.. code-block:: bash
composer require twig/twig:~1.0
Installing from the tarball release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Download the most recent tarball from the `download page`_
2. Verify the integrity of the tarball http://fabien.potencier.org/article/73/signing-project-releases
3. Unpack the tarball
4. Move the files somewhere in your project
Installing the development version
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
git clone git://github.com/twigphp/Twig.git
Installing the PEAR package
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. note::
Using PEAR for installing Twig is deprecated and Twig 1.15.1 was the last
version published on the PEAR channel; use Composer instead.
.. code-block:: bash
pear channel-discover pear.twig-project.org
pear install twig/Twig
Installing the C extension
--------------------------
.. versionadded:: 1.4
The C extension was added in Twig 1.4.
.. note::
The C extension is **optional** but it brings some nice performance
improvements. Note that the extension is not a replacement for the PHP
code; it only implements a small part of the PHP code to improve the
performance at runtime; you must still install the regular PHP code.
Twig comes with a C extension that enhances the performance of the Twig
runtime engine; install it like any other PHP extensions:
.. code-block:: bash
cd ext/twig
phpize
./configure
make
make install
.. note::
You can also install the C extension via PEAR (note that this method is
deprecated and newer versions of Twig are not available on the PEAR
channel):
.. code-block:: bash
pear channel-discover pear.twig-project.org
pear install twig/CTwig
For Windows:
1. Setup the build environment following the `PHP documentation`_
2. Put Twig's C extension source code into ``C:\php-sdk\phpdev\vcXX\x86\php-source-directory\ext\twig``
3. Use the ``configure --disable-all --enable-cli --enable-twig=shared`` command instead of step 14
4. ``nmake``
5. Copy the ``C:\php-sdk\phpdev\vcXX\x86\php-source-directory\Release_TS\php_twig.dll`` file to your PHP setup.
.. tip::
For Windows ZendServer, ZTS is not enabled as mentioned in `Zend Server
FAQ`_.
You have to use ``configure --disable-all --disable-zts --enable-cli
--enable-twig=shared`` to be able to build the twig C extension for
ZendServer.
The built DLL will be available in
``C:\\php-sdk\\phpdev\\vcXX\\x86\\php-source-directory\\Release``
Finally, enable the extension in your ``php.ini`` configuration file:
.. code-block:: ini
extension=twig.so #For Unix systems
extension=php_twig.dll #For Windows systems
And from now on, Twig will automatically compile your templates to take
advantage of the C extension. Note that this extension does not replace the
PHP code but only provides an optimized version of the
``Twig_Template::getAttribute()`` method.
.. _`download page`: https://github.com/twigphp/Twig/tags
.. _`Composer`: https://getcomposer.org/download/
.. _`PHP documentation`: https://wiki.php.net/internals/windows/stepbystepbuild
.. _`Zend Server FAQ`: http://www.zend.com/en/products/server/faq#faqD6
doc/internals.rst 0000664 0000000 0000000 00000011025 13233677763 0014374 0 ustar 00root root 0000000 0000000 Twig Internals
==============
Twig is very extensible and you can easily hack it. Keep in mind that you
should probably try to create an extension before hacking the core, as most
features and enhancements can be handled with extensions. This chapter is also
useful for people who want to understand how Twig works under the hood.
How does Twig work?
-------------------
The rendering of a Twig template can be summarized into four key steps:
* **Load** the template: If the template is already compiled, load it and go
to the *evaluation* step, otherwise:
* First, the **lexer** tokenizes the template source code into small pieces
for easier processing;
* Then, the **parser** converts the token stream into a meaningful tree
of nodes (the Abstract Syntax Tree);
* Eventually, the *compiler* transforms the AST into PHP code.
* **Evaluate** the template: It basically means calling the ``display()``
method of the compiled template and passing it the context.
The Lexer
---------
The lexer tokenizes a template source code into a token stream (each token is
an instance of ``Twig_Token``, and the stream is an instance of
``Twig_TokenStream``). The default lexer recognizes 13 different token types:
* ``Twig_Token::BLOCK_START_TYPE``, ``Twig_Token::BLOCK_END_TYPE``: Delimiters for blocks (``{% %}``)
* ``Twig_Token::VAR_START_TYPE``, ``Twig_Token::VAR_END_TYPE``: Delimiters for variables (``{{ }}``)
* ``Twig_Token::TEXT_TYPE``: A text outside an expression;
* ``Twig_Token::NAME_TYPE``: A name in an expression;
* ``Twig_Token::NUMBER_TYPE``: A number in an expression;
* ``Twig_Token::STRING_TYPE``: A string in an expression;
* ``Twig_Token::OPERATOR_TYPE``: An operator;
* ``Twig_Token::PUNCTUATION_TYPE``: A punctuation sign;
* ``Twig_Token::INTERPOLATION_START_TYPE``, ``Twig_Token::INTERPOLATION_END_TYPE`` (as of Twig 1.5): Delimiters for string interpolation;
* ``Twig_Token::EOF_TYPE``: Ends of template.
You can manually convert a source code into a token stream by calling the
``tokenize()`` method of an environment::
$stream = $twig->tokenize(new Twig_Source($source, $identifier));
.. versionadded:: 1.27
``Twig_Source`` was introduced in version 1.27, pass the source and the
identifier directly on previous versions.
As the stream has a ``__toString()`` method, you can have a textual
representation of it by echoing the object::
echo $stream."\n";
Here is the output for the ``Hello {{ name }}`` template:
.. code-block:: text
TEXT_TYPE(Hello )
VAR_START_TYPE()
NAME_TYPE(name)
VAR_END_TYPE()
EOF_TYPE()
.. note::
The default lexer (``Twig_Lexer``) can be changed by calling
the ``setLexer()`` method::
$twig->setLexer($lexer);
The Parser
----------
The parser converts the token stream into an AST (Abstract Syntax Tree), or a
node tree (an instance of ``Twig_Node_Module``). The core extension defines
the basic nodes like: ``for``, ``if``, ... and the expression nodes.
You can manually convert a token stream into a node tree by calling the
``parse()`` method of an environment::
$nodes = $twig->parse($stream);
Echoing the node object gives you a nice representation of the tree::
echo $nodes."\n";
Here is the output for the ``Hello {{ name }}`` template:
.. code-block:: text
Twig_Node_Module(
Twig_Node_Text(Hello )
Twig_Node_Print(
Twig_Node_Expression_Name(name)
)
)
.. note::
The default parser (``Twig_TokenParser``) can be changed by calling the
``setParser()`` method::
$twig->setParser($parser);
The Compiler
------------
The last step is done by the compiler. It takes a node tree as an input and
generates PHP code usable for runtime execution of the template.
You can manually compile a node tree to PHP code with the ``compile()`` method
of an environment::
$php = $twig->compile($nodes);
The generated template for a ``Hello {{ name }}`` template reads as follows
(the actual output can differ depending on the version of Twig you are
using)::
/* Hello {{ name }} */
class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template
{
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "Hello ";
echo twig_escape_filter($this->env, isset($context["name"]) ? $context["name"] : null), "html", null, true);
}
// some more code
}
.. note::
The default compiler (``Twig_Compiler``) can be changed by calling the
``setCompiler()`` method::
$twig->setCompiler($compiler);
doc/intro.rst 0000664 0000000 0000000 00000005175 13233677763 0013541 0 ustar 00root root 0000000 0000000 Introduction
============
This is the documentation for Twig, the flexible, fast, and secure template
engine for PHP.
If you have any exposure to other text-based template languages, such as
Smarty, Django, or Jinja, you should feel right at home with Twig. It's both
designer and developer friendly by sticking to PHP's principles and adding
functionality useful for templating environments.
The key-features are...
* *Fast*: Twig compiles templates down to plain optimized PHP code. The
overhead compared to regular PHP code was reduced to the very minimum.
* *Secure*: Twig has a sandbox mode to evaluate untrusted template code. This
allows Twig to be used as a template language for applications where users
may modify the template design.
* *Flexible*: Twig is powered by a flexible lexer and parser. This allows the
developer to define their own custom tags and filters, and to create their own DSL.
Twig is used by many Open-Source projects like Symfony, Drupal8, eZPublish,
phpBB, Piwik, OroCRM; and many frameworks have support for it as well like
Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few.
Prerequisites
-------------
Twig needs at least **PHP 5.2.7** to run.
Installation
------------
The recommended way to install Twig is via Composer:
.. code-block:: bash
composer require "twig/twig:~1.0"
.. note::
To learn more about the other installation methods, read the
:doc:`installation` chapter; it also explains how to install
the Twig C extension.
Basic API Usage
---------------
This section gives you a brief introduction to the PHP API for Twig.
.. code-block:: php
require_once '/path/to/vendor/autoload.php';
$loader = new Twig_Loader_Array(array(
'index' => 'Hello {{ name }}!',
));
$twig = new Twig_Environment($loader);
echo $twig->render('index', array('name' => 'Fabien'));
Twig uses a loader (``Twig_Loader_Array``) to locate templates, and an
environment (``Twig_Environment``) to store the configuration.
The ``render()`` method loads the template passed as a first argument and
renders it with the variables passed as a second argument.
As templates are generally stored on the filesystem, Twig also comes with a
filesystem loader::
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
echo $twig->render('index.html', array('name' => 'Fabien'));
.. tip::
If you are not using Composer, use the Twig built-in autoloader::
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
doc/recipes.rst 0000664 0000000 0000000 00000044643 13233677763 0014043 0 ustar 00root root 0000000 0000000 Recipes
=======
.. _deprecation-notices:
Displaying Deprecation Notices
------------------------------
.. versionadded:: 1.21
This works as of Twig 1.21.
Deprecated features generate deprecation notices (via a call to the
``trigger_error()`` PHP function). By default, they are silenced and never
displayed nor logged.
To easily remove all deprecated feature usages from your templates, write and
run a script along the lines of the following::
require_once __DIR__.'/vendor/autoload.php';
$twig = create_your_twig_env();
$deprecations = new Twig_Util_DeprecationCollector($twig);
print_r($deprecations->collectDir(__DIR__.'/templates'));
The ``collectDir()`` method compiles all templates found in a directory,
catches deprecation notices, and return them.
.. tip::
If your templates are not stored on the filesystem, use the ``collect()``
method instead which takes an ``Iterator``; the iterator must return
template names as keys and template contents as values (as done by
``Twig_Util_TemplateDirIterator``).
However, this code won't find all deprecations (like using deprecated some Twig
classes). To catch all notices, register a custom error handler like the one
below::
$deprecations = array();
set_error_handler(function ($type, $msg) use (&$deprecations) {
if (E_USER_DEPRECATED === $type) {
$deprecations[] = $msg;
}
});
// run your application
print_r($deprecations);
Note that most deprecation notices are triggered during **compilation**, so
they won't be generated when templates are already cached.
.. tip::
If you want to manage the deprecation notices from your PHPUnit tests, have
a look at the `symfony/phpunit-bridge
`_ package, which eases the
process a lot.
Making a Layout conditional
---------------------------
Working with Ajax means that the same content is sometimes displayed as is,
and sometimes decorated with a layout. As Twig layout template names can be
any valid expression, you can pass a variable that evaluates to ``true`` when
the request is made via Ajax and choose the layout accordingly:
.. code-block:: jinja
{% extends request.ajax ? "base_ajax.html" : "base.html" %}
{% block content %}
This is the content to be displayed.
{% endblock %}
Making an Include dynamic
-------------------------
When including a template, its name does not need to be a string. For
instance, the name can depend on the value of a variable:
.. code-block:: jinja
{% include var ~ '_foo.html' %}
If ``var`` evaluates to ``index``, the ``index_foo.html`` template will be
rendered.
As a matter of fact, the template name can be any valid expression, such as
the following:
.. code-block:: jinja
{% include var|default('index') ~ '_foo.html' %}
Overriding a Template that also extends itself
----------------------------------------------
A template can be customized in two different ways:
* *Inheritance*: A template *extends* a parent template and overrides some
blocks;
* *Replacement*: If you use the filesystem loader, Twig loads the first
template it finds in a list of configured directories; a template found in a
directory *replaces* another one from a directory further in the list.
But how do you combine both: *replace* a template that also extends itself
(aka a template in a directory further in the list)?
Let's say that your templates are loaded from both ``.../templates/mysite``
and ``.../templates/default`` in this order. The ``page.twig`` template,
stored in ``.../templates/default`` reads as follows:
.. code-block:: jinja
{# page.twig #}
{% extends "layout.twig" %}
{% block content %}
{% endblock %}
You can replace this template by putting a file with the same name in
``.../templates/mysite``. And if you want to extend the original template, you
might be tempted to write the following:
.. code-block:: jinja
{# page.twig in .../templates/mysite #}
{% extends "page.twig" %} {# from .../templates/default #}
Of course, this will not work as Twig will always load the template from
``.../templates/mysite``.
It turns out it is possible to get this to work, by adding a directory right
at the end of your template directories, which is the parent of all of the
other directories: ``.../templates`` in our case. This has the effect of
making every template file within our system uniquely addressable. Most of the
time you will use the "normal" paths, but in the special case of wanting to
extend a template with an overriding version of itself we can reference its
parent's full, unambiguous template path in the extends tag:
.. code-block:: jinja
{# page.twig in .../templates/mysite #}
{% extends "default/page.twig" %} {# from .../templates #}
.. note::
This recipe was inspired by the following Django wiki page:
http://code.djangoproject.com/wiki/ExtendingTemplates
Customizing the Syntax
----------------------
Twig allows some syntax customization for the block delimiters. It's not
recommended to use this feature as templates will be tied with your custom
syntax. But for specific projects, it can make sense to change the defaults.
To change the block delimiters, you need to create your own lexer object::
$twig = new Twig_Environment();
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{#', '#}'),
'tag_block' => array('{%', '%}'),
'tag_variable' => array('{{', '}}'),
'interpolation' => array('#{', '}'),
));
$twig->setLexer($lexer);
Here are some configuration example that simulates some other template engines
syntax::
// Ruby erb syntax
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array(''),
'tag_block' => array(''),
'tag_variable' => array(''),
));
// SGML Comment Syntax
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array(''),
'tag_block' => array(''),
'tag_variable' => array('${', '}'),
));
// Smarty like
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{*', '*}'),
'tag_block' => array('{', '}'),
'tag_variable' => array('{$', '}'),
));
Using dynamic Object Properties
-------------------------------
When Twig encounters a variable like ``article.title``, it tries to find a
``title`` public property in the ``article`` object.
It also works if the property does not exist but is rather defined dynamically
thanks to the magic ``__get()`` method; you just need to also implement the
``__isset()`` magic method like shown in the following snippet of code::
class Article
{
public function __get($name)
{
if ('title' == $name) {
return 'The title';
}
// throw some kind of error
}
public function __isset($name)
{
if ('title' == $name) {
return true;
}
return false;
}
}
Accessing the parent Context in Nested Loops
--------------------------------------------
Sometimes, when using nested loops, you need to access the parent context. The
parent context is always accessible via the ``loop.parent`` variable. For
instance, if you have the following template data::
$data = array(
'topics' => array(
'topic1' => array('Message 1 of topic 1', 'Message 2 of topic 1'),
'topic2' => array('Message 1 of topic 2', 'Message 2 of topic 2'),
),
);
And the following template to display all messages in all topics:
.. code-block:: jinja
{% for topic, messages in topics %}
* {{ loop.index }}: {{ topic }}
{% for message in messages %}
- {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }}
{% endfor %}
{% endfor %}
The output will be similar to:
.. code-block:: text
* 1: topic1
- 1.1: The message 1 of topic 1
- 1.2: The message 2 of topic 1
* 2: topic2
- 2.1: The message 1 of topic 2
- 2.2: The message 2 of topic 2
In the inner loop, the ``loop.parent`` variable is used to access the outer
context. So, the index of the current ``topic`` defined in the outer for loop
is accessible via the ``loop.parent.loop.index`` variable.
Defining undefined Functions and Filters on the Fly
---------------------------------------------------
When a function (or a filter) is not defined, Twig defaults to throw a
``Twig_Error_Syntax`` exception. However, it can also call a `callback`_ (any
valid PHP callable) which should return a function (or a filter).
For filters, register callbacks with ``registerUndefinedFilterCallback()``.
For functions, use ``registerUndefinedFunctionCallback()``::
// auto-register all native PHP functions as Twig functions
// don't try this at home as it's not secure at all!
$twig->registerUndefinedFunctionCallback(function ($name) {
if (function_exists($name)) {
return new Twig_SimpleFunction($name, $name);
}
return false;
});
If the callable is not able to return a valid function (or filter), it must
return ``false``.
If you register more than one callback, Twig will call them in turn until one
does not return ``false``.
.. tip::
As the resolution of functions and filters is done during compilation,
there is no overhead when registering these callbacks.
Validating the Template Syntax
------------------------------
When template code is provided by a third-party (through a web interface for
instance), it might be interesting to validate the template syntax before
saving it. If the template code is stored in a `$template` variable, here is
how you can do it::
try {
$twig->parse($twig->tokenize(new Twig_Source($template)));
// the $template is valid
} catch (Twig_Error_Syntax $e) {
// $template contains one or more syntax errors
}
If you iterate over a set of files, you can pass the filename to the
``tokenize()`` method to get the filename in the exception message::
foreach ($files as $file) {
try {
$twig->parse($twig->tokenize(new Twig_Source($template, $file->getFilename(), $file)));
// the $template is valid
} catch (Twig_Error_Syntax $e) {
// $template contains one or more syntax errors
}
}
.. versionadded:: 1.27
``Twig_Source`` was introduced in version 1.27, pass the source and the
identifier directly on previous versions.
.. note::
This method won't catch any sandbox policy violations because the policy
is enforced during template rendering (as Twig needs the context for some
checks like allowed methods on objects).
Refreshing modified Templates when OPcache or APC is enabled
------------------------------------------------------------
When using OPcache with ``opcache.validate_timestamps`` set to ``0`` or APC
with ``apc.stat`` set to ``0`` and Twig cache enabled, clearing the template
cache won't update the cache.
To get around this, force Twig to invalidate the bytecode cache::
$twig = new Twig_Environment($loader, array(
'cache' => new Twig_Cache_Filesystem('/some/cache/path', Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION),
// ...
));
.. note::
Before Twig 1.22, you should extend ``Twig_Environment`` instead::
class OpCacheAwareTwigEnvironment extends Twig_Environment
{
protected function writeCacheFile($file, $content)
{
parent::writeCacheFile($file, $content);
// Compile cached file into bytecode cache
if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
} elseif (function_exists('apc_compile_file')) {
apc_compile_file($file);
}
}
}
Reusing a stateful Node Visitor
-------------------------------
When attaching a visitor to a ``Twig_Environment`` instance, Twig uses it to
visit *all* templates it compiles. If you need to keep some state information
around, you probably want to reset it when visiting a new template.
This can be easily achieved with the following code::
protected $someTemplateState = array();
public function enterNode(Twig_NodeInterface $node, Twig_Environment $env)
{
if ($node instanceof Twig_Node_Module) {
// reset the state as we are entering a new template
$this->someTemplateState = array();
}
// ...
return $node;
}
Using a Database to store Templates
-----------------------------------
If you are developing a CMS, templates are usually stored in a database. This
recipe gives you a simple PDO template loader you can use as a starting point
for your own.
First, let's create a temporary in-memory SQLite3 database to work with::
$dbh = new PDO('sqlite::memory:');
$dbh->exec('CREATE TABLE templates (name STRING, source STRING, last_modified INTEGER)');
$base = '{% block content %}{% endblock %}';
$index = '
{% extends "base.twig" %}
{% block content %}Hello {{ name }}{% endblock %}
';
$now = time();
$dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('base.twig', '$base', $now)");
$dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('index.twig', '$index', $now)");
We have created a simple ``templates`` table that hosts two templates:
``base.twig`` and ``index.twig``.
Now, let's define a loader able to use this database::
class DatabaseTwigLoader implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface
{
protected $dbh;
public function __construct(PDO $dbh)
{
$this->dbh = $dbh;
}
public function getSource($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return $source;
}
// Twig_SourceContextLoaderInterface as of Twig 1.27
public function getSourceContext($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return new Twig_Source($source, $name);
}
// Twig_ExistsLoaderInterface as of Twig 1.11
public function exists($name)
{
return $name === $this->getValue('name', $name);
}
public function getCacheKey($name)
{
return $name;
}
public function isFresh($name, $time)
{
if (false === $lastModified = $this->getValue('last_modified', $name)) {
return false;
}
return $lastModified <= $time;
}
protected function getValue($column, $name)
{
$sth = $this->dbh->prepare('SELECT '.$column.' FROM templates WHERE name = :name');
$sth->execute(array(':name' => (string) $name));
return $sth->fetchColumn();
}
}
Finally, here is an example on how you can use it::
$loader = new DatabaseTwigLoader($dbh);
$twig = new Twig_Environment($loader);
echo $twig->render('index.twig', array('name' => 'Fabien'));
Using different Template Sources
--------------------------------
This recipe is the continuation of the previous one. Even if you store the
contributed templates in a database, you might want to keep the original/base
templates on the filesystem. When templates can be loaded from different
sources, you need to use the ``Twig_Loader_Chain`` loader.
As you can see in the previous recipe, we reference the template in the exact
same way as we would have done it with a regular filesystem loader. This is
the key to be able to mix and match templates coming from the database, the
filesystem, or any other loader for that matter: the template name should be a
logical name, and not the path from the filesystem::
$loader1 = new DatabaseTwigLoader($dbh);
$loader2 = new Twig_Loader_Array(array(
'base.twig' => '{% block content %}{% endblock %}',
));
$loader = new Twig_Loader_Chain(array($loader1, $loader2));
$twig = new Twig_Environment($loader);
echo $twig->render('index.twig', array('name' => 'Fabien'));
Now that the ``base.twig`` templates is defined in an array loader, you can
remove it from the database, and everything else will still work as before.
Loading a Template from a String
--------------------------------
From a template, you can easily load a template stored in a string via the
``template_from_string`` function (available as of Twig 1.11 via the
``Twig_Extension_StringLoader`` extension):
.. code-block:: jinja
{{ include(template_from_string("Hello {{ name }}")) }}
From PHP, it's also possible to load a template stored in a string via
``Twig_Environment::createTemplate()`` (available as of Twig 1.18)::
$template = $twig->createTemplate('hello {{ name }}');
echo $template->render(array('name' => 'Fabien'));
.. note::
Never use the ``Twig_Loader_String`` loader, which has severe limitations.
Using Twig and AngularJS in the same Templates
----------------------------------------------
Mixing different template syntaxes in the same file is not a recommended
practice as both AngularJS and Twig use the same delimiters in their syntax:
``{{`` and ``}}``.
Still, if you want to use AngularJS and Twig in the same template, there are
two ways to make it work depending on the amount of AngularJS you need to
include in your templates:
* Escaping the AngularJS delimiters by wrapping AngularJS sections with the
``{% verbatim %}`` tag or by escaping each delimiter via ``{{ '{{' }}`` and
``{{ '}}' }}``;
* Changing the delimiters of one of the template engines (depending on which
engine you introduced last):
* For AngularJS, change the interpolation tags using the
``interpolateProvider`` service, for instance at the module initialization
time:
```js
angular.module('myApp', []).config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{[').endSymbol(']}');
});
```
* For Twig, change the delimiters via the ``tag_variable`` Lexer option:
```php
$env->setLexer(new Twig_Lexer($env, array(
'tag_variable' => array('{[', ']}'),
)));
```
.. _callback: http://www.php.net/manual/en/function.is-callable.php
doc/tags/ 0000775 0000000 0000000 00000000000 13233677763 0012602 5 ustar 00root root 0000000 0000000 doc/tags/autoescape.rst 0000664 0000000 0000000 00000004265 13233677763 0015474 0 ustar 00root root 0000000 0000000 ``autoescape``
==============
Whether automatic escaping is enabled or not, you can mark a section of a
template to be escaped or not by using the ``autoescape`` tag:
.. code-block:: jinja
{% autoescape %}
Everything will be automatically escaped in this block
using the HTML strategy
{% endautoescape %}
{% autoescape 'html' %}
Everything will be automatically escaped in this block
using the HTML strategy
{% endautoescape %}
{% autoescape 'js' %}
Everything will be automatically escaped in this block
using the js escaping strategy
{% endautoescape %}
{% autoescape false %}
Everything will be outputted as is in this block
{% endautoescape %}
.. note::
Before Twig 1.8, the syntax was different:
.. code-block:: jinja
{% autoescape true %}
Everything will be automatically escaped in this block
using the HTML strategy
{% endautoescape %}
{% autoescape false %}
Everything will be outputted as is in this block
{% endautoescape %}
{% autoescape true js %}
Everything will be automatically escaped in this block
using the js escaping strategy
{% endautoescape %}
When automatic escaping is enabled everything is escaped by default except for
values explicitly marked as safe. Those can be marked in the template by using
the :doc:`raw` filter:
.. code-block:: jinja
{% autoescape %}
{{ safe_value|raw }}
{% endautoescape %}
Functions returning template data (like :doc:`macros` and
:doc:`parent`) always return safe markup.
.. note::
Twig is smart enough to not escape an already escaped value by the
:doc:`escape` filter.
.. note::
Twig does not escape static expressions:
.. code-block:: jinja
{% set hello = "Hello" %}
{{ hello }}
{{ "world" }}
Will be rendered "Hello **world**".
.. note::
The chapter :doc:`Twig for Developers` gives more information
about when and how automatic escaping is applied.
doc/tags/block.rst 0000664 0000000 0000000 00000000700 13233677763 0014423 0 ustar 00root root 0000000 0000000 ``block``
=========
Blocks are used for inheritance and act as placeholders and replacements at
the same time. They are documented in detail in the documentation for the
:doc:`extends` tag.
Block names should consist of alphanumeric characters, and underscores. Dashes
are not permitted.
.. seealso:: :doc:`block`, :doc:`parent`, :doc:`use`, :doc:`extends`
doc/tags/do.rst 0000664 0000000 0000000 00000000362 13233677763 0013737 0 ustar 00root root 0000000 0000000 ``do``
======
.. versionadded:: 1.5
The ``do`` tag was added in Twig 1.5.
The ``do`` tag works exactly like the regular variable expression (``{{ ...
}}``) just that it doesn't print anything:
.. code-block:: jinja
{% do 1 + 2 %}
doc/tags/embed.rst 0000664 0000000 0000000 00000015640 13233677763 0014416 0 ustar 00root root 0000000 0000000 ``embed``
=========
.. versionadded:: 1.8
The ``embed`` tag was added in Twig 1.8.
The ``embed`` tag combines the behaviour of :doc:`include` and
:doc:`extends`.
It allows you to include another template's contents, just like ``include``
does. But it also allows you to override any block defined inside the
included template, like when extending a template.
Think of an embedded template as a "micro layout skeleton".
.. code-block:: jinja
{% embed "teasers_skeleton.twig" %}
{# These blocks are defined in "teasers_skeleton.twig" #}
{# and we override them right here: #}
{% block left_teaser %}
Some content for the left teaser box
{% endblock %}
{% block right_teaser %}
Some content for the right teaser box
{% endblock %}
{% endembed %}
The ``embed`` tag takes the idea of template inheritance to the level of
content fragments. While template inheritance allows for "document skeletons",
which are filled with life by child templates, the ``embed`` tag allows you to
create "skeletons" for smaller units of content and re-use and fill them
anywhere you like.
Since the use case may not be obvious, let's look at a simplified example.
Imagine a base template shared by multiple HTML pages, defining a single block
named "content":
.. code-block:: text
┌─── page layout ─────────────────────┐
│ │
│ ┌── block "content" ──┐ │
│ │ │ │
│ │ │ │
│ │ (child template to │ │
│ │ put content here) │ │
│ │ │ │
│ │ │ │
│ └─────────────────────┘ │
│ │
└─────────────────────────────────────┘
Some pages ("foo" and "bar") share the same content structure -
two vertically stacked boxes:
.. code-block:: text
┌─── page layout ─────────────────────┐
│ │
│ ┌── block "content" ──┐ │
│ │ ┌─ block "top" ───┐ │ │
│ │ │ │ │ │
│ │ └─────────────────┘ │ │
│ │ ┌─ block "bottom" ┐ │ │
│ │ │ │ │ │
│ │ └─────────────────┘ │ │
│ └─────────────────────┘ │
│ │
└─────────────────────────────────────┘
While other pages ("boom" and "baz") share a different content structure -
two boxes side by side:
.. code-block:: text
┌─── page layout ─────────────────────┐
│ │
│ ┌── block "content" ──┐ │
│ │ │ │
│ │ ┌ block ┐ ┌ block ┐ │ │
│ │ │"left" │ │"right"│ │ │
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ │ └───────┘ └───────┘ │ │
│ └─────────────────────┘ │
│ │
└─────────────────────────────────────┘
Without the ``embed`` tag, you have two ways to design your templates:
* Create two "intermediate" base templates that extend the master layout
template: one with vertically stacked boxes to be used by the "foo" and
"bar" pages and another one with side-by-side boxes for the "boom" and
"baz" pages.
* Embed the markup for the top/bottom and left/right boxes into each page
template directly.
These two solutions do not scale well because they each have a major drawback:
* The first solution may indeed work for this simplified example. But imagine
we add a sidebar, which may again contain different, recurring structures
of content. Now we would need to create intermediate base templates for
all occurring combinations of content structure and sidebar structure...
and so on.
* The second solution involves duplication of common code with all its negative
consequences: any change involves finding and editing all affected copies
of the structure, correctness has to be verified for each copy, copies may
go out of sync by careless modifications etc.
In such a situation, the ``embed`` tag comes in handy. The common layout
code can live in a single base template, and the two different content structures,
let's call them "micro layouts" go into separate templates which are embedded
as necessary:
Page template ``foo.twig``:
.. code-block:: jinja
{% extends "layout_skeleton.twig" %}
{% block content %}
{% embed "vertical_boxes_skeleton.twig" %}
{% block top %}
Some content for the top box
{% endblock %}
{% block bottom %}
Some content for the bottom box
{% endblock %}
{% endembed %}
{% endblock %}
And here is the code for ``vertical_boxes_skeleton.twig``:
.. code-block:: html+jinja

{% block top %}
Top box default content
{% endblock %}

{% block bottom %}
Bottom box default content
{% endblock %}

The goal of the ``vertical_boxes_skeleton.twig`` template being to factor
out the HTML markup for the boxes.
The ``embed`` tag takes the exact same arguments as the ``include`` tag:
.. code-block:: jinja
{% embed "base" with {'foo': 'bar'} %}
...
{% endembed %}
{% embed "base" with {'foo': 'bar'} only %}
...
{% endembed %}
{% embed "base" ignore missing %}
...
{% endembed %}
.. warning::
As embedded templates do not have "names", auto-escaping strategies based
on the template name won't work as expected if you change the context (for
instance, if you embed a CSS/JavaScript template into an HTML one). In that
case, explicitly set the default auto-escaping strategy with the
``autoescape`` tag.
.. seealso:: :doc:`include`
doc/tags/extends.rst 0000664 0000000 0000000 00000016635 13233677763 0015021 0 ustar 00root root 0000000 0000000 ``extends``
===========
The ``extends`` tag can be used to extend a template from another one.
.. note::
Like PHP, Twig does not support multiple inheritance. So you can only have
one extends tag called per rendering. However, Twig supports horizontal
:doc:`reuse`.
Let's define a base template, ``base.html``, which defines a simple HTML
skeleton document:
.. code-block:: html+jinja
{% block head %}
{% block title %}{% endblock %} - My Webpage
{% endblock %}

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:: jinja
{% 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` function. This gives back the results of
the parent block:
.. code-block:: jinja
{% 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:
.. code-block:: jinja
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
Of course, the name after the ``endblock`` word must match the block name.
Block Nesting and Scope
-----------------------
Blocks can be nested for more complex layouts. Per default, blocks have access
to variables from outer scopes:
.. code-block:: jinja
{% 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:: jinja
{% block title %}
{{ page_title|title }}
{% endblock %}
.. code-block:: jinja
{% block title page_title|title %}
Dynamic Inheritance
-------------------
Twig supports dynamic inheritance by using a variable as the base template:
.. code-block:: jinja
{% extends some_var %}
If the variable evaluates to a ``Twig_Template`` or a ``Twig_TemplateWraper``
instance, Twig will use it as the parent template::
// {% extends layout %}
// deprecated as of Twig 1.28
$layout = $twig->loadTemplate('some_layout_template.twig');
// as of Twig 1.28
$layout = $twig->load('some_layout_template.twig');
$twig->display('template.twig', array('layout' => $layout));
.. versionadded:: 1.2
The possibility to pass an array of templates has been added in Twig 1.2.
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:: jinja
{% 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:: jinja
{% 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:: jinja
{# 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:: jinja
{# 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:: jinja
{% for post in posts %}
{{ post.title }}{{ post.text }}
{% endfor %}
Let's take another example: a block included within an ``if`` statement:
.. code-block:: jinja
{% 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:: jinja
{% block head %}
{{ parent() }}
{% if posts is empty %}
{% endif %}
{% endblock head %}
.. seealso:: :doc:`block`, :doc:`block`, :doc:`parent`, :doc:`use`
doc/tags/filter.rst 0000664 0000000 0000000 00000000717 13233677763 0014626 0 ustar 00root root 0000000 0000000 ``filter``
==========
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:: jinja
{% filter upper %}
This text becomes uppercase
{% endfilter %}
You can also chain filters:
.. code-block:: jinja
{% filter lower|escape %}
SOME TEXT
{% endfilter %}
{# outputs "<strong>some text</strong>" #}
doc/tags/flush.rst 0000664 0000000 0000000 00000000432 13233677763 0014454 0 ustar 00root root 0000000 0000000 ``flush``
=========
.. versionadded:: 1.5
The flush tag was added in Twig 1.5.
The ``flush`` tag tells Twig to flush the output buffer:
.. code-block:: jinja
{% flush %}
.. note::
Internally, Twig uses the PHP `flush`_ function.
.. _`flush`: http://php.net/flush
doc/tags/for.rst 0000664 0000000 0000000 00000011051 13233677763 0014120 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:: jinja

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:: jinja
{% 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:: jinja
{% for letter in 'a'..'z' %}
* {{ letter }}
{% endfor %}
The ``..`` operator can take any expression at both sides:
.. code-block:: jinja
{% 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:: jinja
{% 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.
.. versionadded:: 1.2
The ``if`` modifier support has been added in Twig 1.2.
Adding a condition
------------------
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:: jinja

{% 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:: jinja

{% 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:: jinja

Members

{% for key in users|keys %}

{{ key }}

{% endfor %}

Iterating over Keys and Values
------------------------------
You can also access both keys and values:
.. code-block:: jinja

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 ` filter:
.. code-block:: jinja

Top Ten Members

{% for user in users|slice(0, 10) %}

{{ user.username|e }}

{% endfor %}

doc/tags/from.rst 0000664 0000000 0000000 00000000423 13233677763 0014276 0 ustar 00root root 0000000 0000000 ``from``
========
The ``from`` tag imports :doc:`macro` names into the current
namespace. The tag is documented in detail in the documentation for the
:doc:`import` tag.
.. seealso:: :doc:`macro`, :doc:`import`
doc/tags/if.rst 0000664 0000000 0000000 00000003653 13233677763 0013741 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:: jinja
{% 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:: jinja
{% 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:: jinja
{% if not user.subscribed %}

Alternatively you can import names from the template into the current
namespace:
.. code-block:: jinja
{% from 'forms.html' import input as input_field, textarea %}

Username

{{ input_field('username') }}

Password

{{ input_field('password', '', 'password') }}

{{ textarea('comment') }}

.. tip::
To import macros from the current file, use the special ``_self`` variable
for the source.
.. seealso:: :doc:`macro`, :doc:`from`
doc/tags/include.rst 0000664 0000000 0000000 00000005415 13233677763 0014764 0 ustar 00root root 0000000 0000000 ``include``
===========
The ``include`` statement includes a template and returns the rendered content
of that file into the current namespace:
.. code-block:: jinja
{% include 'header.html' %}
Body
{% include 'footer.html' %}
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:: jinja
{# 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:: jinja
{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}
.. code-block:: jinja
{# 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`
chapter and in the :doc:`sandbox` tag documentation.
The template name can be any valid Twig expression:
.. code-block:: jinja
{% 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 %}
// deprecated as of Twig 1.28
$template = $twig->loadTemplate('some_template.twig');
// as of Twig 1.28
$template = $twig->load('some_template.twig');
$twig->display('template.twig', array('template' => $template));
.. versionadded:: 1.2
The ``ignore missing`` feature has been added in Twig 1.2.
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:: jinja
{% include 'sidebar.html' ignore missing %}
{% include 'sidebar.html' ignore missing with {'foo': 'bar'} %}
{% include 'sidebar.html' ignore missing only %}
.. versionadded:: 1.2
The possibility to pass an array of templates has been added in Twig 1.2.
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:: jinja
{% 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.
doc/tags/index.rst 0000664 0000000 0000000 00000000356 13233677763 0014447 0 ustar 00root root 0000000 0000000 Tags
====
.. toctree::
:maxdepth: 1
autoescape
block
do
embed
extends
filter
flush
for
from
if
import
include
macro
sandbox
set
spaceless
use
verbatim
with
doc/tags/macro.rst 0000664 0000000 0000000 00000005650 13233677763 0014443 0 ustar 00root root 0000000 0000000 ``macro``
=========
Macros are comparable with functions in regular programming languages. They
are useful to put often used HTML idioms into reusable elements to not repeat
yourself.
Here is a small example of a macro that renders a form element:
.. code-block:: jinja
{% macro input(name, value, type, size) %}
{% endmacro %}
Macros differ from native PHP functions in a few ways:
* Default argument values are defined by using the ``default`` filter in the
macro body;
* 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.
Import
------
Macros can be defined in any template, and need to be "imported" before being
used (see the documentation for the :doc:`import` tag for more
information):
.. code-block:: jinja
{% 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 functions as items of
the ``forms`` variable.
The macro can then be called at will:
.. code-block:: jinja

{{ forms.input('username') }}

{{ forms.input('password', null, 'password') }}

If macros are defined and used in the same template, you can use the
special ``_self`` variable to import them:
.. code-block:: jinja
{% import _self as forms %}

{{ forms.input('username') }}

.. warning::
When you define a macro in the template where you are going to use it, you
might be tempted to call the macro directly via ``_self.input()`` instead
of importing it; even if seems to work, this is just a side-effect of the
current implementation and it won't work anymore in Twig 2.x.
When you want to use a macro in another macro from the same file, you need to
import it locally:
.. code-block:: jinja
{% 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 %}
Named Macro End-Tags
--------------------
Twig allows you to put the name of the macro after the end tag for better
readability:
.. code-block:: jinja
{% macro input() %}
...
{% endmacro input %}
Of course, the name after the ``endmacro`` word must match the macro name.
.. seealso:: :doc:`from`, :doc:`import`
doc/tags/sandbox.rst 0000664 0000000 0000000 00000001374 13233677763 0014777 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:: jinja
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
.. warning::
The ``sandbox`` tag is only available when the sandbox extension is
enabled (see the :doc:`Twig for Developers` 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:: jinja
{% sandbox %}
{% for i in 1..2 %}
{{ i }}
{% endfor %}
{% endsandbox %}
doc/tags/set.rst 0000664 0000000 0000000 00000003222 13233677763 0014126 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:: jinja
{% set foo = 'bar' %}
After the ``set`` call, the ``foo`` variable is available in the template like
any other ones:
.. code-block:: jinja
{# displays bar #}
{{ foo }}
The assigned value can be any valid :ref:`Twig expressions
`:
.. code-block:: jinja
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
Several variables can be assigned in one block:
.. code-block:: jinja
{% 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:: jinja
{% set 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.
doc/tags/use.rst 0000664 0000000 0000000 00000006534 13233677763 0014140 0 ustar 00root root 0000000 0000000 ``use``
=======
.. versionadded:: 1.1
Horizontal reuse was added in Twig 1.1.
.. 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:: jinja
{% 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:: jinja
{% 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:: jinja
{# 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:: jinja
{% 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:: jinja
{% extends "base.html" %}
{% use "blocks.html" with sidebar as base_sidebar, title as base_title %}
{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
.. versionadded:: 1.3
The ``parent()`` support was added in Twig 1.3.
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:: jinja
{% 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::
In Twig 1.2, renaming allows you to simulate inheritance by calling the
"parent" block:
.. code-block:: jinja
{% 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.
doc/tags/verbatim.rst 0000664 0000000 0000000 00000001156 13233677763 0015150 0 ustar 00root root 0000000 0000000 ``verbatim``
============
.. versionadded:: 1.12
The ``verbatim`` tag was added in Twig 1.12 (it was named ``raw`` before).
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:: jinja
{% verbatim %}

{% for item in seq %}

{{ item }}

{% endfor %}

{% endverbatim %}
.. note::
The ``verbatim`` tag works in the exact same way as the old ``raw`` tag,
but was renamed to avoid confusion with the ``raw`` filter. doc/tags/with.rst 0000664 0000000 0000000 00000002165 13233677763 0014313 0 ustar 00root root 0000000 0000000 ``with``
========
.. versionadded:: 1.28
The ``with`` tag was added in Twig 1.28.
Use the ``with`` tag to create a new inner scope. Variables set within this
scope are not visible outside of the scope:
.. code-block:: jinja
{% 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:: jinja
{% 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:
{% set bar = 'bar' %}
{% with { foo: 42 } only %}
{# only foo is defined #}
{# bar is not defined #}
{% endwith %}
doc/templates.rst 0000664 0000000 0000000 00000065400 13233677763 0014401 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 simply a 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 logic
of the template.
Below is a minimal template that illustrates a few basics. We will cover further
details later on:
.. code-block:: html+jinja
My Webpage

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 prints the
result of an expression to the template.
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.
You can use a dot (``.``) to access attributes of a variable (methods or
properties of a PHP object, or items of a PHP array), or the so-called
"subscript" syntax (``[]``):
.. code-block:: jinja
{{ foo.bar }}
{{ foo['bar'] }}
When the attribute contains special characters (like ``-`` that would be
interpreted as the minus operator), use the ``attribute`` function instead to
access the variable attribute:
.. code-block:: jinja
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
.. 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.
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`).
.. 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, return a ``null`` value.
``foo['bar']`` on the other hand only works with PHP arrays:
* check if ``foo`` is an array and ``bar`` a valid element;
* if not, return a ``null`` value.
.. note::
If you want to access a dynamic attribute of a variable, use the
:doc:`attribute` function instead.
Global Variables
~~~~~~~~~~~~~~~~
The following variables are always available in templates:
* ``_self``: references the current template;
* ``_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:: jinja
{% 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 (``|``) and may have optional arguments in
parentheses. 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:: jinja
{{ name|striptags|title }}
Filters that accept arguments have parentheses around the arguments. This
example will join a list by commas:
.. code-block:: jinja
{{ list|join(', ') }}
To apply a filter on a section of code, wrap it in the
:doc:`filter` tag:
.. code-block:: jinja
{% filter upper %}
This text becomes uppercase
{% endfilter %}
Go to the :doc:`filters` page to learn more about built-in
filters.
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:: jinja
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
Go to the :doc:`functions` page to learn more about the
built-in functions.
Named Arguments
---------------
.. versionadded:: 1.12
Support for named arguments was added in Twig 1.12.
.. code-block:: jinja
{% 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:: jinja
{{ 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:: jinja
{# 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:: jinja
{{ "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:: jinja

Members

{% for user in users %}

{{ user.username|e }}

{% endfor %}

The :doc:`if` tag can be used to test an expression:
.. code-block:: jinja
{% 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:: jinja
{# 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:: jinja
{{ 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:: jinja
{% for box in boxes %}
{{ include('render_box.html') }}
{% endfor %}
The included template ``render_box.html`` is able to access the ``box`` variable.
The filename of the template depends on the template loader. For instance, the
``Twig_Loader_Filesystem`` allows you to access other templates by giving the
filename. You can access templates in subdirectories with a slash:
.. code-block:: jinja
{{ 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.
Sounds complicated but it is very basic. It's easier to understand it by
starting with an example.
Let's define a base template, ``base.html``, which defines a simple HTML
skeleton document that you might use for a simple two-column page:
.. code-block:: html+jinja
{% block head %}
{% block title %}{% endblock %} - My Webpage
{% 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:: jinja
{% 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:: jinja
{% 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 with the so called horizontal reuse
with the help of the :doc:`use` tag. This is an advanced feature
hardly ever needed in regular templates.
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 you don't trust.
Escaping works by piping the variable through the
:doc:`escape` or ``e`` filter:
.. code-block:: jinja
{{ user.username|e }}
By default, the ``escape`` filter uses the ``html`` strategy, but depending on
the escaping context, you might want to explicitly use any other available
strategies:
.. code-block:: jinja
{{ 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:: jinja
{% 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:: jinja
{% 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:: jinja
{{ '{{' }}
For bigger sections it makes sense to mark a block
:doc:`verbatim`.
Macros
------
.. versionadded:: 1.12
Support for default argument values was added in Twig 1.12.
Macros are comparable with functions in regular programming languages. They
are useful to reuse often used HTML fragments to not repeat yourself.
A macro is defined via the :doc:`macro` tag. Here is a small example
(subsequently called ``forms.html``) of a macro that renders a form element:
.. code-block:: jinja
{% macro input(name, value, type, size) %}
{% endmacro %}
Macros can be defined in any template, and need to be "imported" via the
:doc:`import` tag before being used:
.. code-block:: jinja
{% import "forms.html" as forms %}

{{ forms.input('username') }}

Alternatively, you can import individual macro names from a template into the
current namespace via the :doc:`from` tag and optionally alias them:
.. code-block:: jinja
{% from 'forms.html' import input as input_field %}

Username

{{ input_field('username') }}

Password

{{ input_field('password', '', 'password') }}

A default value can also be defined for macro arguments when not provided in a
macro call:
.. code-block:: jinja
{% macro input(name, value = "", type = "text", size = 20) %}
{% endmacro %}
If extra positional arguments are passed to a macro call, they end up in the
special ``varargs`` variable as a list of values.
.. _twig-expressions:
Expressions
-----------
Twig allows expressions everywhere. These work very similar to regular PHP and
even if you're not working with PHP you should feel comfortable with it.
.. note::
The operator precedence is as follows, with the lowest-precedence
operators listed first: ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``,
``==``, ``!=``, ````, ``>=``, ``<=``, ``in``, ``matches``,
``starts with``, ``ends with``, ``..``, ``+``, ``-``, ``~``, ``*``, ``/``,
``//``, ``%``, ``is``, ``**``, ``|``, ``[]``, and ``.``:
.. code-block:: jinja
{% set greeting = 'Hello ' %}
{% set name = 'Fabien' %}
{{ greeting ~ name|lower }} {# Hello fabien #}
{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}
Literals
~~~~~~~~
.. versionadded:: 1.5
Support for hash keys as names and expressions was added in Twig 1.5.
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 just
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:: jinja
{# keys as string #}
{ 'foo': 'foo', 'bar': 'bar' }
{# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
{ foo: 'foo', bar: 'bar' }
{# keys as integer #}
{ 2: 'foo', 4: 'bar' }
{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
{ (1 + 1): 'foo', (a ~ 'b'): 'bar' }
* ``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:: jinja
{% set foo = [1, {"foo": "bar"}] %}
.. tip::
Using double-quoted or single-quoted strings has no impact on performance
but string interpolation is only supported in double-quoted strings.
Math
~~~~
Twig allows you to calculate with values. This is rarely useful in templates
but exists for completeness' sake. The following operators are supported:
* ``+``: Adds two objects 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``.
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 support 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:: jinja
{% 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:: jinja
{% 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:: jinja
{# 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:: jinja
{% 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:: jinja
{# find out if a variable is odd #}
{{ name is odd }}
Tests can accept arguments too:
.. code-block:: jinja
{% if post.status is constant('Post::PUBLISHED') %}
Tests can be negated by using the ``is not`` operator:
.. code-block:: jinja
{% 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
~~~~~~~~~~~~~~~
.. versionadded:: 1.12.0
Support for the extended ternary operator was added in Twig 1.12.0.
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 just syntactic sugar for the :doc:`range` function):
.. code-block:: jinja
{{ 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:: jinja
(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 an object.
* ``?:``: The ternary operator:
.. code-block:: jinja
{{ foo ? 'yes' : 'no' }}
{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
* ``??``: The null-coalescing operator:
.. code-block:: jinja
{# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }}
String Interpolation
~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 1.5
String interpolation was added in Twig 1.5.
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:: jinja
{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}
.. _templates-whitespace-control:
Whitespace Control
------------------
.. versionadded:: 1.1
Tag level whitespace control was added in Twig 1.1.
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.
Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
.. code-block:: jinja
{% spaceless %}

foo bar

{% endspaceless %}
{# output will be

foo bar

#}
In addition to the spaceless tag you can also control whitespace on a per tag
level. By using the whitespace control modifier on your tags, you can trim
leading and or trailing whitespace:
.. code-block:: jinja
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
{{- value -}}
{%- endif -%}
{# output 'no spaces' #}
The above sample shows the default whitespace control modifier, and how you can
use it to remove whitespace around tags. Trimming space will consume all whitespace
for that side of the tag. It is possible to use whitespace trimming on one side
of a tag:
.. code-block:: jinja
{% set value = 'no spaces' %}