Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4: Multiple inclusion of a file

Here is my base.html.twig

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% include 'flashes/page-title.html.twig' %}</title>
</head>
    <body>
        <h1>{% include 'flashes/page-title.html.twig' %}</h1>
    </body>
</html>

I'm wondering why twig includes only once this file ?

like image 244
dovstone Avatar asked Jan 31 '26 04:01

dovstone


1 Answers

When you get a flash message from the flashbag, the message gets cleared at the same time. You can see this in Symfony's documentation of flash messages as well as in the FlashBagInterface API.

So my guess is that Twig includes the file twice, but the second time the flashbag is just empty. That's why you don't get anything for the h1 tag. You can confirm this by putting something static (e.g. simply Hello world) to the flashes/page-title.html.twig file and see whether the file gets included twice.

You could instead use the peek() method to retrieve the message while keeping it in the bag, i.e. something like {% for title in app.flashes.peek('title') %} or {% for title in app.session.flashbag.peek('title') %} if the former doesn't work. But then the message wouldn't get cleared. It might or might not be a problem in your case.

Could something else than flash messages be a better approach in this case?

like image 57
Matias Kinnunen Avatar answered Feb 03 '26 11:02

Matias Kinnunen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!