问题
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.
I know I can pass the $page_title
variable to Controller:render
but I don't want to add
{% block title %}
{{ page_title }}
{% endblock %}
to every single action template.
回答1:
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 %}
Start a base layout template with the title block
{# 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 %}
part is not necessary but useful if you ever want to override or append to it (using parent()
)
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>
Extend this base layout with every child template
{# 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 %}
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!',
));
来源:https://stackoverflow.com/questions/27178919/symfony-set-block-content-from-controller