技術めも

テンプレートエンジンTwig

リンク

オフィシャルサイト
http://twig.sensiolabs.org/

【PHP】Twigまとめ
https://qiita.com/assa/items/4fef2f3abd95248ed626

フィルタ
https://github.com/masakielastic/twig-ja/blob/master/02-Twig-for-Template-Designers.markdown

{% set status = constant('\\App\\Lib\\Hoge\\Fuga::STATUS') %}

文法

文字切り詰め

{{ name | length > 32 ? name | slice(0, 14) ~ '…' : name }}

ナンバー

{{  200.35 | number_format }}

定数アクセス

{{ constant('App\\Demo\\Test::DEMO') }}

Tag一覧

http://twig.sensiolabs.org/doc/tags/index.html

include

{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}

{# no variables will be accessible #}
{% include 'template.html' only %}

split

{% set foo = "one,two,three"|split(',') %}

フィルタ

http://twig.sensiolabs.org/doc/filters/index.html

default

{{ var|default('var is not defined') }}
{{ var.foo|default('foo item on var is not defined') }}
{{ var['foo']|default('foo item on var is not defined') }}
{{ ''|default('passed var is empty')  }}

文法

if 構文

{% if mobile == false %}
    ……
{% endif %}

foreach

{% for word in dic.words %}
    ……
{% endfor %}
{% for key, item in article %}
    <li>{{ key }}:{{ item.title }}</li>
{% endfor %}

for

{% for num in 0..10 %}
    {{ num }}
{% endfor %}

in_array

{% if id in array %}

その他

{% set index = 0 %}
{% set index = index + 1 %}
{% set index = "Hello" ~ "World" %}
{{ w.description | raw | nl2br }}

レイアウト

  • hoge.twig
{{% extends "layout.html" %}

{% block content %}
      Content of the page...
{% endblock %}
  • layout.twig
<!DOCTYPE html>
<html lang="ja">
   <head>
       <meta charset="utf-8">
       <title>{{ header.title }}</title>
   </head>
   <body>
       {% block content %}{% endblock %}
   </body>
</html>

本番DEBUG

<!-- DEBUG表示 -->
<script>
console.log("[debug] sql: "+{{ debug.sql }});
console.log("[debug] xml: "+{{ debug.xml }});
console.log("[debug] pager: "+{{ debug.pager }});
</script>