我有一個控制器用於設置存儲在數據庫中的一些東西。幾乎控制器類似:在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