In my Symfony controller I provide an error message via FlashBag like so:
$this->get('session')->getFlashBag()->add('error', 'The code you provided didn\'t match what we expected.');
This renders the expected output, is it possible for me to add a link? So I would be able to output a message like:
The code you provided doesn't match what we expected, if you have continued trouble, consider looking into common problems and how to solve them.
I've already tried adding in it in using markdown and HTML syntax, neither of which work, the documentation on the feature does not say if it is or is not possible, and there are currently no questions on SO that address this.
Instead of manually creating a safe string in one instance and then using the raw
filter for all your flash messages you can also create a Twig\Markup
object (see e.g. this and this StackOverflow answer) and put that one in the flash bag.
(The code below is an extension of Chris's answer.)
Bad: Using raw
, which applies to all flash messages
// PHP Controller
$newPageUrl = $this->generateUrl('core_page_id', ['id' => $page->getId()]);
$this->addFlash('success',
sprintf('Page updated! <a href="%s">View page</a>', $newPageUrl)
);
<!-- your Twig template -->
{% for message in app.flashes('success') %}
<div class="flash-notice alert alert-success"><i class="fa fa-check"></i> {{ message|raw }}</div>
{% endfor %}
Better: Using Twig\Markup
This approach does not generally circumvent Twig's escaping mechanism and it allows for cleaner separation of controller logic and template design.
There is no HTML markup being built in the PHP code:
// PHP Controller
public function yourAction() {
// ...
$message = new Twig\Markup(
$this->renderView('flashes/page_update.html.twig', ['page' => $page]),
'UTF-8'
);
$this->addFlash('success', $message);
// With Symfony 4.x,
// the argument $message of method `addFlash` is type-hinted
// as `string`. You need to get to the session directly, e.g.
// by injecting `SessionInterface $session` into the method
// and then call:
// $session->getFlashBag()->add('success', $message);
}
You can use all Twig features you know and love for your flash messages:
<!-- flashes/page_update.html.twig -->
Page updated! <a href="{{ path('core_page_id', {id:page.id}) }}">View page</a>
The base template retains a clean message display logic with automatic escaping still in place:
<!-- your Twig template -->
{% for message in app.flashes('success') %}
<div class="flash-notice alert alert-success"><i class="fa fa-check"></i> {{ message }}</div>
{% endfor %}
By default Twig will escape HTML to prevent any injection.
You have to add a filter that prevent your HTML from escape.
{{ flashMessage|raw }}
http://twig.sensiolabs.org/doc/filters/raw.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With