Blade
Blade is a powerful, simple, and elegant templating engine provided with Laravel, but it can also be used separately in any PHP project. In the context of the theme, Blade is used to separate the application logic from the presentation logic, making your code cleaner, more maintainable, and easier to understand.
By using Blade, you can:
- Keep your HTML structure separate from your PHP code.
- Use convenient shortcuts for PHP control structures.
- Reuse code snippets across different views with Blade’s layout system.
When to use Blade
Section titled “When to use Blade”You should use Blade whenever you need to generate HTML or other text-based formats. It’s especially useful when:
- You have complex PHP logic that you want to keep separate from your HTML.
- You want to reuse certain parts of your HTML across multiple pages (like headers, footers, etc.).
- You want to keep your code DRY (Don’t Repeat Yourself).
How to use Blade
Section titled “How to use Blade”In our child theme, the Blade templating engine is already initialized in the App class in app/App.php file. To use it, you need to call the static render method of the Blade class, which is defined in the app/Blade.php file.
Here’s a basic example
// Render a view with dataecho view('path.to.view', ['key' => 'value']);In this example, 'path.to.view' is the path to the Blade template file in the views directory, and ['key' => 'value'] is an associative array of data that you want to pass to the view.
SVG files
Section titled “SVG files”We’ve included an SVG helper method to make it easier to include SVG files in your Blade templates. You can use the svg method to include an SVG file like this:
<a class="button" href="/some-link"> @svg('icon') Click me</a>This will compile into:
<a class="button" href="/some-link"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <!-- SVG content here --> </svg> Click me</a>In this example, icon is the name of the SVG file located in the assets/svg directory. The svg method will automatically generate the correct <svg> tag with the contents of the SVG file.
Examples
Section titled “Examples”Here’s an example of a Blade template file
<html> <body> <h1>Hello, {{ $name }}!</h1> </body></html>And here’s how you can render this view with data
// Render the view with dataecho view('example', ['name' => 'John Doe']);This will output
<html> <body> <h1>Hello, John Doe!</h1> </body></html>In the Blade template, you can use {{ $variable }} to output a variable, and you can use Blade’s control structures to add logic to your views.
<html> <body> @if ($name === 'John Doe') <h1>Hello, John Doe!</h1> @else <h1>Hello, stranger!</h1> @endif </body></html>For more information on how to use Blade, you can refer to the Blade documentation.