54

GitHub - spatie/laravel-view-components: A better way to connect data with view...

 5 years ago
source link: https://github.com/spatie/laravel-view-components
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

A better way to connect data with view rendering in Laravel

Latest Version on Packagist Build Status StyleCI Quality Score Total Downloads

View components are a way to help organize logic tied to view, similar to view composers.

namespace App\Http\ViewComponents;

use Illuminate\Http\Request;
use Illuminate\Contracts\Support\Htmlable;

class NavigationComponent implements Htmlable
{
    /** \Illuminate\Http\Request */
    private $request;

    /** @var string */
    private $backgroundColor;

    public function __construct(Request $request, string $backgroundColor)
    {
        $this->request = $request;
        $this->backgroundColor = $backgroundColor;
    }

    public function toHtml(): string
    {
        return view('components.navigation', [
            'activeUrl' => $this->request->url(),
            'backgroundColor' => $this->backgroundColor,
        ]);
    }
}
@render('navigation', ['backgroundColor' => 'black'])

A view component can be anything that implements Laravel's Htmlable contract, so you don't necessarily need to use Blade views to render the component. This is useful for wrapping third party HTML packages, like spatie/laravel-menu.

namespace App\Http\ViewComponents;

use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Contracts\Auth\Guard;
use Spatie\Menu\Laravel\Menu;

class MainMenuComponent implements Htmlable
{
    /** @var \Illuminate\Contracts\Auth\Guard */
    private $guard;

    /** @var string */
    private $class;

    public function __construct(Guard $guard, string $class = null)
    {
        $this->guard = $guard;
        $this->class = $class;
    }

    public function toHtml(): string
    {
        $menu = Menu::new()
            ->addClass($this->class)
            ->url('/', 'Home')
            ->url('/projects', 'Projects');

        if ($this->guard->check()) {
            $menu->url('/admin', 'Adminland');
        }

        return $menu;
    }
}
@render('mainMenu', ['class' => 'background-green'])

The benefit over view composers is that data and rendering logic are explicitly tied together in components instead of being connected afterwards. They also allow you to seamlessly combine properties and dependency injection.

This package is based on Introducing View Components in Laravel, an alternative to View Composerss by Jeff Ochoa.

Installation

You can install the package via composer:

composer require spatie/laravel-view-components

No additional setup necessary. Laravel will automatically discover and register the service provider.

Optionally you can publish the config file with:

php artisan vendor:publish --provider="Spatie\ViewComponents\ViewComponentsServiceProvider" --tag="config"

This is the default content of the file that will be published at config/view-components:

return [
    /*
     * The root namespace where components reside. Components can be referenced
     * with camelCase & dot notation.
     *
     * Example: 'root_namespace' => App\Http\ViewComponents::class
     *
     * `@render('myComponent')
     *     => `App\Http\ViewComponents\MyComponent`
     */
    'root_namespace' => 'App\Http\ViewComponents',

    /*
     * Register alternative namespaces here, similar to custom view paths.
     *
     * Example: 'navigation' => App\Services\Navigation::class,
     *
     * `@render('navigation::mainMenu')`
     *     => `App\Services\Navigation\MainMenu`
     */
    'namespaces' => [
        // 'navigation' => App\Services\Navigation::class,
    ],
];

Usage

The @render directive

The @render Blade directive accepts two arguments: the first is the view component's path or class name, the second is an extra set of properties (optional).

You can choose between referincing the component via a path or a class name.

@render('myComponent')
@render(App\Http\ViewComponents\MyComponent::class)

Parameters will be injected in the view components __construct method. The component is instantiated with Laravel's container, so parameters that aren't provided by render will be automatically injected.

use Illuminate\Http\Request;

class MyComponent implements Htmlable
{
    public function __construct(Request $request, string $color)
    {
        $this->request = $request;
        $this->color = $color;
    }

    // ...
}
@render('myComponent', ['color' => 'red'])

In the above example, $color is explicitly set, and a $request object will be injected by Laravel.

Configuration

The root namespace

By configuring root_namespace, you can define where the bulk of your view components are located. By default, this is in App\Http\ViewComponents.

app/
  Http/
    ViewComponents/
      MyComponent.php
      Nested/
        NestedComponent.php

The above components can be rendered with @render('myComponent') and @render('nested.nestedComponent').

Additional namespaces

You can register additional namespaces in the namespaces configuration, similar to view paths.

return [
    'namespaces' => [
        'navigation' => App\Services\Navigation::class,
    ],
];
app/
  Services/
    Navigation/
      Menu.php

The above Menu component can now be rendered with @render('navigation::menu').

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

Support us

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License

The MIT License (MIT). Please see License File for more information.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK