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">
<ul>
@foreach ($errors->all() as $error)
	<li>{{ $error }}</li>
@endforeach</ul>
</div>
@endif 

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">
<ul>
{% for error in errors.all() %}
	<li>{{ error }}</li>
{% endfor %}</ul>
</div>
{% 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!

Advertisements

3 thoughts 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s