intro.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. Introduction
  2. ============
  3. This is the documentation for Twig, the flexible, fast, and secure template
  4. engine for PHP.
  5. If you have any exposure to other text-based template languages, such as
  6. Smarty, Django, or Jinja, you should feel right at home with Twig. It's both
  7. designer and developer friendly by sticking to PHP's principles and adding
  8. functionality useful for templating environments.
  9. The key-features are...
  10. * *Fast*: Twig compiles templates down to plain optimized PHP code. The
  11. overhead compared to regular PHP code was reduced to the very minimum.
  12. * *Secure*: Twig has a sandbox mode to evaluate untrusted template code. This
  13. allows Twig to be used as a template language for applications where users
  14. may modify the template design.
  15. * *Flexible*: Twig is powered by a flexible lexer and parser. This allows the
  16. developer to define their own custom tags and filters, and to create their own DSL.
  17. Twig is used by many Open-Source projects like Symfony, Drupal8, eZPublish,
  18. phpBB, Piwik, OroCRM; and many frameworks have support for it as well like
  19. Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few.
  20. Prerequisites
  21. -------------
  22. Twig needs at least **PHP 7.0.0** to run.
  23. Installation
  24. ------------
  25. The recommended way to install Twig is via Composer:
  26. .. code-block:: bash
  27. composer require "twig/twig:^2.0"
  28. Basic API Usage
  29. ---------------
  30. This section gives you a brief introduction to the PHP API for Twig.
  31. .. code-block:: php
  32. require_once '/path/to/vendor/autoload.php';
  33. $loader = new \Twig\Loader\ArrayLoader([
  34. 'index' => 'Hello {{ name }}!',
  35. ]);
  36. $twig = new \Twig\Environment($loader);
  37. echo $twig->render('index', ['name' => 'Fabien']);
  38. Twig uses a loader (``\Twig\Loader\ArrayLoader``) to locate templates, and an
  39. environment (``\Twig\Environment``) to store the configuration.
  40. The ``render()`` method loads the template passed as a first argument and
  41. renders it with the variables passed as a second argument.
  42. As templates are generally stored on the filesystem, Twig also comes with a
  43. filesystem loader::
  44. $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
  45. $twig = new \Twig\Environment($loader, [
  46. 'cache' => '/path/to/compilation_cache',
  47. ]);
  48. echo $twig->render('index.html', ['name' => 'Fabien']);