# 编码标准

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

## 编码标准

在编写Twig模板时，我们建议您遵循以下官方编码标准:

* 在分隔符({、{ %和{ #)的开头和分隔符(}、% }和# }结束之前)放置一个(和仅一个)空格。

```markup
{{ foo }}
{# comment #}
{% if foo %}{% endif %}
```

当使用空格控制字符时，不要在它和分隔符之间放置空格:

```
{{- foo -}}
{#- comment -#}
{%- if foo -%}{%- endif -%}
```

* 在下列操作符前后放置一个(并且只有一个)空格:比较运算符(= =，!=、<、>、> =、< =)、数学操作符(+、-、/、\* %,/ / \* \*),逻辑运算符(,,),\~,,,和三元操作符(?):

```markup
{{ 1 + 2 }}
{{ foo ~ bar }}
{{ true ? true : false }}
```

* 放置一个(并且只有一个)空格:在散列中，在数组和散列中:

```markup
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
```

* 在开括号之后，不要在括号结束之前放任何空格。

```markup
{{ 1 + (2 * 3) }}
```

* 在字符串分隔符之前和之后，不要放置任何空格:

```markup
{{ 'foo' }}
{{ "foo" }}
```

* 在下列操作符之前和之后，不要放置空格|, ., .., \[]:

```
{{ foo|upper|lower }}
{{ user.name }}
{{ user[name] }}
{% for i in 1..12 %}{% endfor %}
```

* 不要在括号之前和之后放置任何空格，用于过滤和函数调用:

```
{{ foo|default('foo') }}
{{ range(1..10) }}
```

* 在打开和结束数组和散列之后，不要放置任何空格。

```
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
```

* 使用小写和下划算来命名变量名:

```markup
{% set foo = 'foo' %}
{% set foo_bar = 'foo' %}
```

* 在标签内缩进你的代码(使用与已呈现模板的目标语言相同的缩进):

```markup
{% block foo %}
    {% if true %}
        true
    {% endif %}
{% endblock %}
```


---

# 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/bian-ma-biao-zhun.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.
