灵活,快速和安全的PHP模板引擎:Twig

jopen 9年前

Twig是一个灵活,快速和安全的PHP模板引擎。Twig 使用的语法类似于Django 和 Jinja 模板语言。

Twig is a modern template engine for PHP

  • 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 its own custom tags and filters, and create its own DSL.

Why yet another template engine?

When it comes to template engines in PHP, many people will tell you that PHP itself is a template engine. But even if PHP started its life as a template language, it did not evolve like one in the recent years. As a matter of fact, it doesn't support many features modern template engines should have nowadays:

  • Concise: The PHP language is verbose and becomes ridiculously verbose when it comes to output escaping:

    In comparison, Twig has a very concise syntax, which make templates more readable:

  • Template oriented syntax: Twig has shortcuts for common patterns, like having a default text displayed when you iterate over an empty array:

  • Full Featured: Twig supports everything you need to build powerful templates with ease: multiple inheritance, blocks, automatic output-escaping, and much more:

  • Easy to learn: The syntax is easy to learn and has been optimized to allow web designers to get their job done fast without getting in their way.

Of course, PHP is also the language for which you can find the more template engine projects. But most of them are still developed with PHP4 in mind, and do not embrace web development best practices:

  • Extensibility: Twig is flexible enough for all your needs, even the most complex ones. Thanks to an open architecture, you can implement your own language constructs (tags, filters, functions, and even operators) to create your very own DSL.

  • Unit tested: Twig is fully unit-tested. The library is stable and ready to be used in large projects.

  • Documented: Twig is fully documented, with a dedicated online book, and of course a full API documentation.

  • Secure: When it comes to security, Twig has some unique features:

    • Clean Error Messages: Whenever you have a syntax problem within a template, Twig outputs a helpful message with the filename and the line number where the problem occurred. It eases the debugging a lot.

    • Fast: One of the goals of Twig is to be as fast as possible. To achieve the best speed possible, Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.

    项目主页:http://www.open-open.com/lib/view/home/1413959879559