Mage2 E commerce Module Views

# Module View Files

namespace Mage2\HelloWorld\Controllers;

use Illuminate\Http\Request;
use Mage2\Framework\System\Controllers\Controller;

class IndexController extends Controller
{
    public function index(Request $request)
    {
        $name = $request->get('name','World');
        return view('mage2-hello-world::index.index')
                    ->with('name', $name);
    }

}

 

#To check if view exists

use Illuminate\Support\Facades\View;

if (View::exists('mage2-hello-world::index.index')) {
    // return view here
}

 

#Pass an Argument to view

return view('mage2-hello-world')->with('name', $name)

//Another way
return view('mage2-hello-world',['name' => $name]);

 

#View Composer

Mage2 View Composer is callback or class methods that is been called before the view about to rendered. Let say you want to pass an admin navigation to Admin nav.blade.php We can use View composer. Step 1: Open your Module.php

use Illuminate\Support\Facades\View;
                    /**
 * Register bindings in the container.
 *
 * @return  void
 */
public function register()
{
      View::composer(
            'mage2-hello-world', 'Mage2\HelloWorld\ViewComposers\HelloWorldFieldComposer'
        );

    // Use Same composer for mutliple views

    View::composer(
            ['mage2-hello-world::index.create','mage2-hello-world::index.edit'],
                'Mage2\HelloWorld\ViewComposers\HelloWorldFieldComposer'
        );

}

Create an file inside your module ViewComposers folder called HelloWorldFieldComposer.php

namespace Mage2\HelloWorld\ViewComposers;

use Illuminate\View\View;

class HelloWorldFieldComposer
{

    /**
     * Bind data to the view.
     *
     * @param    View $view
     * @return  void
     */
    public function compose(View $view)
    {
        $name = "Jack Sparrow";
        $view->with('name', $name);
    }

}