gpt4 book ai didi

php - Symfony 从 Controller 设置 block 内容

转载 作者:搜寻专家 更新时间:2023-10-31 22:02:08 24 4
gpt4 key购买 nike

有没有办法在 Symfony 的 Controller 中设置模板 block 内容?

有没有办法在 Controller 中做这样的事情?

$this->get('templating')->setBlockContent('page_title', $page_title);

我需要动态设置页面标题,并且我想避免修改每个单独的操作模板。

我知道我可以将 $page_title 变量传递给 Controller:render 但我不想添加

{% block title %}
{{ page_title }}
{% endblock %}

每个 Action 模板。

最佳答案

由于任何父 Twig 模板都处理传递给其子模板的变量,因此有一种更简单的方法可以实现您想要执行的操作。事实上,此方法基本等同于从 Controller 将内容写入整个 block ,因为我们本质上只是使用 {% block %} 将传递的 render 变量直接插入到内容中{{ 变量}}{% 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>

{% 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!',
));

关于php - Symfony 从 Controller 设置 block 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com