Symfony lock block content from controller

Is there a way to set the content of a template block from 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 a dynamic page title and I want to avoid changing every action template.

I know I can pass a variable $page_title

to Controller:render

, but I don't want to add

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

      

for each action template.

+3


source to share


1 answer


Since any Twig parent templates handle variables that are passed to their child templates, there is an easier way to achieve what you want to do. In fact, this method is the main equivalent of writing the content to the entire block from the controller, since we essentially just insert the passed variable render

directly into the content using{% block %}{{ variable }}{% endblock %}

Run Master Layout Template with 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 part is {% block %}

not needed, but useful if you ever want to override or add it (using parent()

)

You can also add the site name so that page_title

you can add if it exists:



<title>{% block title %}{{ page_title is defined ? page_title ~ ' | ' }}Acme Industries Inc.{% endblock %}</title>

      

Extend this basic layout with each 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 page_title

to your function render

that references your child template

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

      

0


source







All Articles