LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【Symfony2】twigレンダリング基礎知識

Last updated at Posted at 2018-03-18

Symfony2で標準サポートされているテンプレートエンジンtwigの使い方メモ。

twigはフランスのSensioLabsがスポンサードしている標準バンドルパッケージ。

構文には以下の2種類がある。

① 変数や式の結果をテンプレートに出力します。
{ {・・・} }

②テンプレートのロジックを制御するタグで、forループなどの命令実行に利用されます。
{ %・・・% }

Symfony2を利用しなくても、公式サイトからダウンロードすれば単体で利用可能。

テンプレートは継承可能

ヘッダー/フッターなど共通テンプレート化すれば、他テンプレートでも柔軟に利用可能。

base.html.twigを継承するテンプレートは{ % block body % }にHTML記載。

base.html.twig
<div id="sidebar">
    { % block sidebar % }
        <ul>
            <li><a href="/">ホーム</a></li>
            <li><a href="/blog">ブログ</a></li>
        </ul>
    { % endblock % }
</div>
<div id="content">
    { % block body  % }{ %  endblock  % }
</div>

base.html.twigを継承したテンプレートでは、block bodyの中にロジックを記載している。

test.html.twig
{ % extends '::base.html.twig' %}

{ % block title %}ブログ記事の一覧{ % endblock % }

{ % block body % }
    { % for entry in blog_entries % }
        <h2>{ { entry.title } }</h2>
        <p>{ { entry.body } }</p>
    { % endfor % }
{ % endblock % }

例では配列[blog_entries]の要素から[title]と[body]を表示。

for文で配列要素にアクセスする方法

配列要素にアクセスするには配列変数.要素名でアクセスする。

test.html.twig
{ % for item in navigation % }
    <li>item.index</li>
{ % endfor % }

twigでのif文処理の方法

PHPのif構文と同じ様にif 〜 else構文で制御。

test.html.twig
{ % if item is empty % }
    <p>商品の在庫がありません!</p>
{ % else % }
    <p>商品に在庫があります!</p>
{ % endif % }

フォームレンダリング処理方法

フォームフィールドのラベルやエラーをを簡単に表示することが可能。

test.html.twig
//twig上での記載
<div>
    { { form_label(form.age) } }
    { { form_errors(form.age) } }
    { { form_widget(form.age) } }
</div>

//HTMLへレンダリングされると以下のようになります。
<div>
    <label for="form_age">Age</label>
    <ul>
        <li>This field is required</li>
    </ul>
    <input type="number" id="form_age" name="form[age]">
</div>

Formでレンダリングしてみる

Symfony2ではFormクラスを利用すればレンダリングやバリデーションチェックを簡単に行え、以下ControllerクラスではSampleIndexTypeのインスタンスを引数にcreatFormを呼び出す。

SampleController.php
//SampleController.php
namespace Test\SampleBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Test\SampleBundle\Form\Type\SampleIndexType;
use Test\SampleBundle\Entity\SampleEntity;

class SampleController extends Controller 
{
    public function indexAction()
    {
        $form = $this->createForm(new SampleIndexType, null);
        return $this->render(
               'SampleBundle:Default:index.html.twig', array("form" => $form->createView()));
    }
}

引数のSampleIndexTypeではレンダリングしたForm要素定義。

SampleIndexType.php
//SampleIndexType.php
namespace Test\SampleBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SampleIndexType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('textTest', 'text', array('required' => false));

        $builder->add('checkTest', 'choice', array(
            'choices' => array(
                1 => 'あり',
                2 => 'なし'
            ),
            'expanded' => true,
            'multiple' => true,
            'data' => array(1, 2)
        ));

    }

    public function getName()
    {
        return 'test';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('csrf_protection' => false));
    }
}

今回のForm定義ではテキストフィールドとチェックボックスを定義。

テキストフィールド定義では引数として、array(‘required’ => false)で必須入力チェックをOFFにする設定になる。何も記載しなければtrueとなり、HTML5のrequire属性がtrueで設定される。

//テキストフィールルド
{ { form_label(form.textTest, 'テスト件数', {'label_attr' : {'class': 'middle'} }) } }
{ { form_widget(form.textTest, { 'attr': {'class': 'form-control'} }) } }

//チェックボックス
{ { form_label(form.checkTest, '', {'label_attr' : {'class': 'middle'} }) } }
{ % for checkTestChildren in form.checkTest % }
    { { form_widget(checkTestChildren) } }
    { { checkTestChildren.vars.label } }
{ % endfor % }

twig上でForm要素をレンダリングする際にはform_widgetを利用。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up