# 介绍

> 原文：[Introduction](https://twig.sensiolabs.org/doc/2.x/intro.html)\
> 翻译：小虾米（QQ:509129）

## 介绍

这是Twig的文档，灵活，快速，安全的PHP模板引擎。

如果您对其他基于文本的模板语言有任何接触，如Smarty、Django或Jinja，用Twig您应该会有熟悉的感觉。通过坚持PHP的原则和添加对模板环境有用的功能以至于对设计人员和开发人员很友好。

主要特点是…

* 快速:Twig将模板编译成普通的优化PHP代码。与普通PHP代码相比，开销减少到最低限度。
* 安全:Twig有一个沙盒模式来评估不受信任的模板代码。这使得Twig可以用作应用程序的模板语言，用户可以在其中修改模板设计。
* 灵活性:Twig由一个灵活的lexer和解析器驱动。这允许开发人员定义自己的自定义标记和过滤器，并创建他们自己的DSL。

Twig被许多开源项目所使用，如Symfony、Drupal8、eZPublish、phpBB、Piwik、OroCRM;以及许多框架都支持它，如Slim、Yii、Laravel、Codeigniter和Kohana——只是举几个例子。

### 先决条件

Twig至少需要**PHP 7.0.0**来运行。

### 安装

推荐的安装Twig的方法是通过Composer:

```
composer require "twig/twig:^2.0"
```

> 要了解更多关于其他安装方法的信息，请阅读安装章节;它还解释了如何安装Twig C扩展。

### 基于API的用法

本节向您简要介绍了Twig的PHP API。

```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使用一个加载器(Twig\_Loader\_Array)来定位模板，以及一个环境(Twig\_Environment)来存储配置。

render()方法加载模板作为第一个参数传递，并将渲染的变量参数作为第二个参数传递。

由于模板通常存储在文件系统中，Twig还附带了一个文件系统加载器:

```php
$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'));
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://twig.shujuwajue.com/twig-2x/jie-shao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
