有没有办法从Symfony的控制器中设置模板块内容?
有没有办法从控制器内部做这样的事情?
$this->get('templating')->setBlockContent('page_title', $page_title);
我需要动态设置页面标题,并且希望避免修改每个操作模板。
我知道我可以将$page_title
变量传递给Controller:render
但我不想添加
{% block title %}
{{ page_title }}
{% endblock %}
到每个操作模板。
由于任何父 Twig 模板都处理传递给其子模板的变量,因此有一种更简单的方法可以实现您想要执行的操作。实际上,此方法等效于将内容从控制器写入整个块,因为我们本质上只是使用{% block %}{{ variable }}{% endblock %}
将传递的render
变量直接插入内容
使用标题栏启动基本布局模板
{# Resources/views/base.html.twig #}
<html>
<head>
<title>{% block title %}{{ page_title is defined ? page_title }}{% endblock %}</title>
{# ... Rest of your HTML base template #}
</html>
{% block %}
部分不是必需的,但如果您想覆盖或附加它(使用 parent()
)
您还可以添加站点范围的标题,以便可以附加page_title
(如果存在):
<title>{% block title %}{{ page_title is defined ? page_title ~ ' | ' }}Acme Industries Inc.{% endblock %}</title>
使用每个子模板扩展此基本布局
{# Resources/views/Child/template.html.twig #}
{% extends '::base.html.twig' %}
{# You can even re-use the page_title for things like heading tags #}
{% block content %}
<h1>{{ page_title }}</h1>
{% endblock %}
将page_title
传递到引用子模板的render
函数中
return $this->render('AcmeBundle:Child:template.html.twig', array(
'page_title' => 'Title goes here!',
));