2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Symfony2.7のコントローラーからTwigに変数を渡す

Posted at

参考書籍:http://amzn.to/2hR0rdQ

コントローラーの$this->render第二引数に配列で渡すと、Twig側で拾えます。

###before

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class ConcertController extends Controller
{
    /**
     * @Route("/page/")
     **/
    public function indexAction()
    {
        return $this->render('Page/index.html.twig');
    }
}

###after

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class ConcertController extends Controller
{
    /**
     * @Route("/page/")
     **/
    public function indexAction()
    {
        $information = "add new concert";
        $args = [
            'informations' => [
                '201610' => 'Add new page',
                '201611' => 'Add news page',
                '201612' => 'Delete old page',
            ],
            'title' => 'Example Site'
        ];
        return $this->render(
            'Page/index.html.twig',
            $args
        );
    }
}

##Twigで拾う
渡した値は、第二引数のキー名で拾えます。

<html>
<body>
    <h1>{{ title }}</h1>
    <ul>
        {% for key, item in informations %}
            <li>{{ key }}: {{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

###出力
スクリーンショット 2016-12-30 1.43.52.png

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?