有没有办法在 Symfony 的控制器中设置模板块内容?
有没有办法在控制器中执行类似的操作?
$this->get('templating')->setBlockContent('page_title', $page_title);
我需要动态设置页面标题,并且希望避免修改每个操作模板。
我知道我可以通过$page_title
变量为Controller:render
但我不想添加
{% block title %}
{{ page_title }}
{% endblock %}
到每一个动作模板。
由于任何父 Twig 模板都会处理传递给其子模板的变量,因此有一种更简单的方法可以实现您想要执行的操作。事实上,此方法基本相当于将内容从控制器写入整个块,因为我们本质上只是插入一个传递的render
使用变量直接进入内容{% block %}{{ variable }}{% endblock %}
使用标题栏启动基本布局模板
{# 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>
The {% 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!',
));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)