3
0

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.

Symfony3のTwigでGlobal値を利用する方法

Last updated at Posted at 2018-10-12

概要

TwigでGlobal値を利用する場合はconfig.ymlで読み込むか、Twigの拡張を利用する方法がある
基本は前者でよいと思うが管理方法は人それぞれなので二種類メモしておく

動作環境

  • Symfony 3.4.15
  • Twig 2.5.0

方法1:config.ymlに定義する

config.yml
# Twig Configuration
twig:
    globals:
        # parametersから読み込む場合
        base_url: '%base_url%'
        site:
            name: 'テストサイト'

config.ymlの肥大化を防ぎたい場合はtwig.ymlとかに書いてimportすれば良い

templateで使う

sample.twig
{{ site.name }}

Controllerで使う

<?php
    /**
     * @Route("/", name="sample")
     * @Method("GET")
     */
    public function sampleAction()
    {
        $twigGlobalValues = $this->get('twig')->getGlobals();
        dump(site_name)
    }

方法2:Twigの拡張設定を行って定義する

yamlにGlobal値を定義する

src/AppBundle/Resources/config/global_params.yml
site:
    name: 'テストサイト'

twigの拡張設定をする

src/AppBundle/Twig/AppExtension.php
<?php
namespace AppBundle\Twig;

use \Symfony\Component\Yaml\Yaml;
class AppExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{

    /**
     * Global値を取得する
     * @return array
     */
    public function getGlobals()
    {
        $app_global = Yaml::parseFile(__DIR__.'/../Resources/config/global_params.yml');

        return array(
            'app_global' => $app_global,
        );
    }

}

templateで使う

sample.twig
{{ app_global.site.name }}

controllerで使う

<?php
    /**
     * @Route("/", name="sample")
     * @Method("GET")
     */
    public function sampleAction()
    {
        $twigGlobalValues = $this->get('twig')->getGlobals();
        dump($twigGlobalValues['app_global']);
    }
3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?