PHP › Template Engines (Blade & Twig)

What are Blade components and Twig macros, and how do they help you create reusable pieces of template markup that can be used consistently across many different pages?

Intermediate

Answer

Blade components and Twig macros both let you define a reusable, self contained piece of template markup once, such as a styled button, a form input field, or an alert message box, optionally accepting parameters to customize its appearance or content each time it is used, and then reuse that same defined piece of markup consistently across many different pages throughout an application, which avoids duplicating the same markup repeatedly and makes updating that shared component's appearance in the future a matter of changing just one central definition.
{{-- Blade component usage --}}
<x-alert type="success" :message="$message" />

{# Twig macro definition #}
{% macro alert(type, message) %}
    <div class="alert alert-{{ type }}">{{ message }}</div>
{% endmacro %}
Real-world example A design system defines a single reusable alert Blade component accepting a type and message, letting every page throughout the application display consistently styled alert messages by reusing that same one central component definition.

Common follow-ups: What is the difference between a Blade component and a simple Blade include?;How do you pass more complex data, such as an array or an object, into a Blade component or a Twig macro?