Zend 表现力 - 布局 [英] Zend expressive - Layout

查看:34
本文介绍了Zend 表现力 - 布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的布局 (Twig) 中,我想从 中间件身份验证.

In my layout (Twig), i'd like to retrieve a value from a Middleware authentication.

如果我把,在templates.global.pĥp:

If i put, in templates.global.pĥp:

'twig' => [
        'globals' => [
            // Variables to pass to all twig templates
            'auth' => (new \Zend\Authentication\AuthenticationService())->hasIdentity(),
        ],
    ],

在布局 default.html.twig

And in layout default.html.twig

{% if auth %}
    Connect
{% else %}
    Not connect
{% endif %}

此代码有效,但是,这是一个好方法吗?

This code works, but, is it a good method ?

谢谢:)

推荐答案

这不是一个好方法.首先,使用配置文件设置全局模板数据是针对静态数据的.如果要缓存配置,在配置中创建服务将失败.我不知道 zend 拍卖服务,但最好从服务管理器或您正在使用的任何其他容器中获取它.这样您就可以确保在您的应用程序中的任何地方都使用相同的服务.

It's not a good method. First of all, using the config files to set global template data is meant for static data. Creating a service in the config will fail if you want to cache the config. I don't know about the zend auction service, but it would be better to get it from the service manager or any other container you are using. This way you make sure that everywhere in your application the same service is being used.

对于模板中需要的常见变量或服务,我在 模板渲染器.因此,我没有调用原始模板渲染器,而是调用我自己的类,并在其中使用通用数据填充模板.

For common variables or services which are needed in templates, I have a wrapper around the TemplateRenderer. So instead of calling the original template renderer, I call my own class and in there I populate the template with common data.

您还可以使用 TemplateRendererInterface::addDefaultParam.在任何其他中间件中,您可以注入模板渲染器,设置所需的默认数据,然后在您的模板中访问它.

And you can also inject default parameters with TemplateRendererInterface::addDefaultParam. In any other middleware you can inject the templaterenderer, set the desired default data and later on access it in your templates.

这篇关于Zend 表现力 - 布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆