#代碼規范
在編寫Twig模版時,我們推薦使用以下這些官方編碼規范:
* 在起始定界符(``{{``, ``{%``,
and ``{#``)的后面加一個空格,并在結尾定界符(``}}``, ``%}``, and ``#}``)前面加一個空格:
~~~
{{ foo }}
{# comment #}
{% if foo %}{% endif %}
~~~
在使用空白控制字符時,不要在它和定界符之間添加任何空格:
{{- foo -}}
{#- comment -#}
{%- if foo -%}{%- endif -%}
* 在以下操作符前后添加一個空格:比較運算符 (``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``), 數學運算符 (``+``, ``-``, ``/``, ``*``, ``%``, ``//``, ``**``), 邏輯運算符 (``not``, ``and``, ``or``), ``~``, ``is``, ``in``, 以及三元運算符(``?:``):
~~~
{{ 1 + 2 }}
{{ foo ~ bar }}
{{ true ? true : false }}
~~~
* 在散列中的``:``后添加一個空格,散列和數組的``,``后也添加一個空格:
~~~
{{ [1, 2, 3] }}
{{ {'foo': 'bar'} }}
~~~
* 不要在表達式的圓括號前后添加空格:
` {{ 1 + (2 * 3) }}`
* 不要在字符串分隔符前后添加空格:
~~~
{{ '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'} }}
~~~
* 變量名必須包含小寫字母和下劃線:
~~~
{% set foo = 'foo' %}
{% set foo_bar = 'foo' %}
~~~
* 在標簽內縮進代碼(使用與模板渲染的目標語言相同的縮進方式)
~~~
{% block foo %}
{% if true %}
true
{% endif %}
{% endblock %}
~~~
- 首頁
- 目錄
- 介紹
- 安裝
- 面向模板設計師
- 面向開發者
- 擴展 Twig
- Twig的內部構建
- 棄用的特性
- 使用技巧
- 代碼規范
- 標簽 tags
- autoescape
- block
- do
- embed
- extends
- filter
- flush
- for
- from
- if
- import
- include
- macro
- sandbox
- set
- spaceless
- use
- verbatim
- 過濾器
- abs
- batch
- capitalize
- convert_encoding
- date
- date_modify
- default
- escape
- first
- format
- join
- json_encode
- keys
- last
- length
- lower
- merge
- nl2br
- number_format
- raw
- replace
- reverse
- round
- slice
- sort
- split
- striptags
- title
- trim
- upper
- url_encode
- 函數
- attribute
- block
- constant
- cycle
- date
- dump
- include
- max
- min
- parent
- random
- range
- source
- template_from_string
- 測試
- constant
- defined
- divisibleby
- empty
- even
- iterable
- null
- odd
- sameas