How to display errors in Laravel 5.4 with Twig / TwigBridge

As Laravel ships with Blade, the Laravel manual gives templating examples in Blade.

For displaying basic variables in a Twig template, it’s pretty simple:

{{ title }}

However, it takes slightly more effort to display form validation errors.

If you’re implementing authentication in Laravel and you generate the relevant auth classes, you’ll be given a batch of Blade templates. Not much good if you prefer Twig.

Here’s a Blade code snippet from the Validation quickstart guide:

@if ($errors->any())
<div class="alert alert-danger">
@foreach ($errors->all() as $error)
	<li>{{ $error }}</li>

It doesn’t take too long to translate this into Twig syntax, but to save you some time (and to stop you wondering if it’ll even work in Twig), here’s the equivalent Twig code.

{% if errors.any() %}
<div class="alert alert-danger">
{% for error in errors.all() %}
	<li>{{ error }}</li>
{% endfor %}</ul>
{% endif %} 

And if you don’t want to cut and paste this everywhere that you need it, why not create a Twig template with the above code inside, and simply include the template when you need it?

Easy when you know how!


One thought on “How to display errors in Laravel 5.4 with Twig / TwigBridge

  1. Pingback: How to minimise CRUD front-end code duplication in Laravel 5.4 / Twig – Ben Barden

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s