我有一个控制器用于设置存储在数据库中的一些东西。几乎控制器类似:在Symfony 3的基础布局中使用树枝扩展
class SetupController extends Controller
{
protected $foreground = '#fff';
protected $background = '#333';
protected $logo = 'default.png';
protected $show_logo = true;
public function HomePageAction()
{
...
$options = [
...
'logo' => $this->logo,
'foreground' => $this->foreground,
'background' => $this->background
];
return $this->render('CommonBundle:Layout:topbar_info.html.twig', ['options' => $options]);
}
}
如何。我正在使用/app/Resources/views/base.html.twig
该功能(这是我的布局)如下:
<head>
...
{% block stylesheets %}
...
<style type="text/css" media="all">
.background, .dynamic_color {
background-color: {{ options.background }};
}
</style>
{% endblock %}
</head>
<body>
<div id="logo_id_area_container" class="topbar">
{{ render(controller('CommonBundle:Setup:HomePage')) }}
</div>
</body>
当我尝试以使其失败,出现以下页面错误:
Variable "options" does not exist.
当然,我想使用它不存在,因为出来的CommonBundle:Setup:HomePage
行动的变种,
做任何人们知道一个更好的方法来实现这一目标
经过一番研究,我想出了使用枝条延伸,但我失去了一些东西,因为没有按照我的预期工作。我的枝条扩展的代码看起来像上面的:
class SetupExtension extends \Twig_Extension
{
use MMISessionTools;
protected $em, $session, $zend, $session_record, $storage;
protected $foreground = '#fff', $background = '#333', $logo = 'default.png', $show_logo = true;
public function __construct(
RegistryInterface $em,
SessionInterface $session,
ZendBridge $zb,
) {
$this->em = $em;
$this->session = $session;
$this->zend = $zb;
// Start the session before lookup for the required data
$session->start();
// Vars for internal usage
$this->session_record = $record = $em->getRepository('CommonBundle:Session')->find($session->getId());
$this->storage = $this->UnserializeSessionData(explode('|', $record->getData())[1])['storage'];
}
public function renderLogo()
{
$logo = $this->storage->show_logo &&
$this->storage instanceof \stdClass &&
file_exists("/images/icons/logos/{$this->storage->prefix}_{$this->storage->host_companies_id}.gif")
? $this->storage->prefix.'_'.$this->storage->host_companies_id.'.gif'
: $this->logo;
return '<a href=""><img src="/images/icons/logos/'.$logo.'" alt="" height="60"></a>';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('render_logo', 'renderLogo', ['is_safe' => ['html']]),
];
}
}
我从base.html.twig
调用它(主要布局或基本模板)如下:
{{ render_logo() }}
但我结束了以下错误:
CRITICAL - Call to undefined function renderLogo() CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\UndefinedFunctionException: "Attempted to call function "renderLogo" from the global namespace."
我已经注册了如下扩展在services.yml
:
setup.twig_extension:
class: CommonBundle\Twig\SetupExtension
arguments: ['@doctrine','@session', '@zend_bridge']
tags:
- { name: twig.extension }
还有什么我在这里失踪?我正在使用Symfony 3.2.5