ZF2 - 将变量从Module.php渲染到twig布局

时间:2013-11-28 17:53:32

标签: variables layout module zend-framework2 twig

我正在将ZF2站点从使用默认模板转换为twig版本,到目前为止,对于主要部分,一切进展顺利,除了我在从引导方法定义的Module.php中有一些变量我现在无法进入layout.twig模板。

适用于默认模板的原始代码如下:

public function bootstrapLayout(MvcEvent $e)
{
    $config = $e->getApplication()->getServiceManager()->get('applicationconfig');
    $authService = $e->getApplication()->getServiceManager()->get('AuthService');

    $version = new \stdClass();
    $version->major = $config['version']['major'];
    $version->minor = $config['version']['minor'];

    $dt = new \DateTime();

    $thisYear = $dt->format('Y');

    $dt->setTimestamp($config['version']['build_date']);
    $version->buildDate = $dt->format('d/m/Y H:i');

    $user = new \stdClass();
    $user->hasIdentity = $authService->hasIdentity();
    $user->username = $authService->getStorage()->read('username');

    $e->getViewModel()->setVariables(array(
        'version' => $version,
        'thisYear' => $thisYear,
        'user' => $user,
    ));
}

但是,'version','thisYear'和'user'都不会让树枝布局模板知道。我在这里搜索过,我找到的最接近的解决方案是通过以下方式获得ZfcTwigRenderer:

$zfcTwigRenderer = $e->getApplication()->getServiceManager()->get('ZfcTwigRenderer');

但现在我不知道如何利用它并将我定义的变量通过它传递给布局。

以下是布局文件的内容:

{{ docType() }}
<html lang="en" class="no-js">
    <head>
        <meta charset="utf-8">
        <title>{% block title %}{% endblock title %} - Website</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        {% block meta %}{% endblock meta %}

        <!-- Le styles -->
        <link href="/css/bootstrap.min.css" media="screen" rel="stylesheet" type="text/css">
        <link href="/css/bootstrap-hidden-inline.css" media="screen" rel="stylesheet" type="text/css">
        <link href="/css/theme.min.css" media="screen" rel="stylesheet" type="text/css">
        <link href="/css/bootstrap-datetimepicker.min.css" media="screen" rel="stylesheet" type="text/css">
        <link href="/css/style.css" media="screen" rel="stylesheet" type="text/css">
        <link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">
        {% block style %}{% endblock style %}

        <!-- Scripts -->
        <script type="text/javascript" src="/js/jquery.min.js"></script>
        <script type="text/javascript" src="/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="/js/tooltip.min.js"></script>
        <script type="text/javascript" src="/js/bootstrap-datetimepicker.min.js"></script>
        <!--[if lt IE 9]><script type="text/javascript" src="/js/html5.js"></script><![endif]-->
        <script type="text/javascript" src="/js/modernizr.min.js"></script>
        <script type="text/javascript" src="/js/overlays.min.js"></script>
        <script type="text/javascript" src="/js/common.min.js"></script>
        {% block script %}{% endblock script %}
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-static-top">
            <div class="container">
                <div class="navbar-header">
                    {% if user.hasIdentity %}
                        <button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse" type="button">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                    {% endif %}
                    <a class="navbar-brand" href="{{ url('home') }}">Website</a>
                </div>
                <div class="collapse navbar-collapse">
                    <ul class="nav navbar-nav">
                        <!--<li><a class="icon-home" href="{{ url('home') }}"><span></span>Home</a></li>-->
                        {% if user.hasIdentity %}
                            <li class="hidden-sm hidden-xs"><a class="icon-import" href="{{ url('import') }}"><span></span>Import</a></li>
                            <li class="hidden-sm hidden-xs"><a class="icon-export" href="{{ url('export') }}"><span></span>Export</a></li>
                            <li><a class="icon-about" href="{{ url('about') }}"><span></span>About</a></li>
                            <!-- <li><a class="icon-reports" href="#"><span></span>Reports</a></li> -->
                            <li><a class="icon-logout" href="{{ url('logout') }}"><span></span>Logout</a></li>
                        {% endif %}
                    </ul>
                    <ul class="nav navbar-nav navbar-right">
                        {% if user.hasIdentity %}
                            <!--<li><a class="icon-report-bug" href="{{ url('report-bug') }}"><span></span>Report bug</a></li>-->
                        {% endif %}
                    </ul>
                </div>
            </div>
        </div>
        {% if user.hasIdentity %}
            <div class="container hidden-sm hidden-xs">
                <div class="welcome-message"><span></span>Welcome {{ user.username }}</div>
            </div>
        {% endif %}
        <div class="container">
            {% block content %}{{ content|raw }}{% endblock content %}
            <hr>
            <footer>
                Copyright &copy; {{ thisYear }} Company name<br>
                Version {{ version.major }}.{{ version.minor }} &mdash;
                Build {{ version.buildDate }}
            </footer>
        </div> <!-- /container -->
        {% block inline %}{% endblock inline %}
    </body>
</html>

尽管在过去的几个小时内尝试了各种各样的事情,但我真的遇到了死胡同,所以对此有任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:0)

您可以使用

current ($e->getViewModel ()->getChildren ())->setVariables(array(
    'version' => $version,
    'thisYear' => $thisYear,
    'user' => $user,
));

而不是

$e->getViewModel()->setVariables(array(
    'version' => $version,
    'thisYear' => $thisYear,
    'user' => $user,
));    

答案 1 :(得分:0)

对于所有布局中可用的真实全局变量,您需要在Module.php中的onBootstrap函数内执行以下操作,因此您的示例将是

public function bootstrapLayout(MvcEvent $e)
{
    $config = $e->getApplication()->getServiceManager()->get('applicationconfig');
    $authService = $e->getApplication()->getServiceManager()->get('AuthService');

    $version = new \stdClass();
    $version->major = $config['version']['major'];
    $version->minor = $config['version']['minor'];

    $dt = new \DateTime();

    $thisYear = $dt->format('Y');

    $dt->setTimestamp($config['version']['build_date']);
    $version->buildDate = $dt->format('d/m/Y H:i');

    $user = new \stdClass();
    $user->hasIdentity = $authService->hasIdentity();
    $user->username = $authService->getStorage()->read('username');

    $enviroment = $e->getApplication()->getServiceManager()->get('ZfcTwigEnvironment');
    $enviroment->addGlobal('version', $version);
    $enviroment->addGlobal('thisYear', $thisYear);
    $enviroment->addGlobal('user', $user);
}

这样您就可以像上面一样使用上面的模板了。

希望这有帮助

答案 2 :(得分:-1)

AHAH!在对网络上的ZF2概念进行了一些挖掘之后,我已经设法提出了一个解决方案。也许,也许不是,最好的,但它的工作(至少现在)...解决方案是一个自定义视图助手。

Module.php 中,我添加了一个getViewHelperConfig()方法,我计划通过globalVars()拨打电话:

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'globalVars' => function($helperPluginManager) {
                    $serviceLocator = $helperPluginManager->getServiceLocator();
                    $viewHelper = new View\Helper\GlobalVars();
                    $viewHelper->setServiceLocator($serviceLocator);
                    return $viewHelper;
                }
        ),
    );
}

然后我在 Application \ src \ Application \ View \ Helper \ GlobalVars.php 中创建了视图助手:

<?php
namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceManager;

class GlobalVars extends AbstractHelper
{
    protected $serviceLocator;

    public function __invoke()
    {
        $config = $this->serviceLocator->get('applicationconfig');
        $authService = $this->serviceLocator->get('AuthService');

        $dateTime = new \DateTime();
        $date = new \stdClass();
        $date->thisYear = $dateTime->format('Y');

        $dateTime->setTimestamp($config['version']['build_date']);

        $version = new \stdClass();
        $version->major = $config['version']['major'];
        $version->minor = $config['version']['minor'];
        $version->buildDate = $dateTime->format('d/m/Y H:i');

        $user = new \stdClass();
        $user->hasIdentity = $authService->hasIdentity();
        $user->username = $authService->getStorage()->read('username');

        return array(
            'version' => $version,
            'date' => $date,
            'user' => $user,
        );
    }

    public function setServiceLocator(ServiceManager $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
    }
}

layout.twig 中,我现在通过{{ globalVars().version.major }}调用此方法,并检查用户是否已登录,{% if globalVars().user.hasIdentity %}

如果某人有更好/更优雅的方法,那么我肯定会有兴趣看到它,但如果没有,或者这是“最佳”方法,那么希望它对其他人也有用。