Symfony 从控制器设置块内容 [英] Symfony set block content from controller

查看:23
本文介绍了Symfony 从控制器设置块内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Symfony 的控制器中设置模板块内容?

Is there a way to set a template block content from within a controller in Symfony?

有没有办法在控制器中做这样的事情?

Is there a way to do something like this from within a controller?

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

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

I need to set the page title dynamically and I want to avoid modifying every single action template.

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

I know I can pass the $page_title variable to Controller:render but I don't want to add

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

到每一个动作模板.

推荐答案

由于任何父 Twig 模板都会处理传递给其子模板的变量,因此有一种更简单的方法可以实现您想要执行的操作.事实上,这个方法是从控制器将内容写入整个块的基本等价物,因为我们本质上只是使用 {% block %} 将传递的 render 变量直接插入到内容中{{ 变量 }}{% endblock %}

Since any parent Twig templates handle variables that are passed to their children templates, there's a simpler method to achieve what you want to do. In fact, this method is the basic equivalent of writing content into an entire block from the controller since we're essentially just inserting a passed render variable directly into the contents using {% 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>

{% block %} 部分不是必需的,但如果您想覆盖或附加到它(使用 parent())

The {% block %} part is not necessary but useful if you ever want to override or append to it (using parent())

您还可以添加站点范围的标题,以便可以附加 page_title(如果存在):

You can also add a site-wide title so the page_title can be appended if it exists:

<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 函数中

Pass the page_title into your render function which references your child template

return $this->render('AcmeBundle:Child:template.html.twig', array(
    'page_title' => 'Title goes here!',
));

这篇关于Symfony 从控制器设置块内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆