Twig is a powerful, yet easy to master template engine. It is also my personal favorite as all my web development is based on either Symfony or Silex.
Apart from its core syntax ({{ ... }} and {% ... %}), Twig has built-in support for various filters. A filter is like a “converter”. It receives certain original data (a string, a number, a date, etc) and by applying a conversion, outputs the data in a new form (as a string, a number, a date, etc). For example, the number_format filter can convert a number into a more readable one:
{{price|number_format(2, '.', ',')}}
Assuming price is a variable with value 1234567.12345, after the filter operation, the output in the page will be 1,234,567.12: 2 decimal places, “.” as the decimal point and “,” as the thousands separator. This makes it much more readable.
As another example, capitalize will make every first letter of a word in a sentence uppercase and others lowercase:
{{title|capitalize}}
Assuming title is a variable with the value this tutorial is nice, after the filter operation, the output will be This Tutorial Is Nice.
Twig has a number of built-in filters. The full list can be found in its official documentation.
Continue reading %Building a Custom Twig Filter the TDD Way%
by Taylor Ren via SitePoint
No comments:
Post a Comment