Laravel5.1 Learning Note 7 view

Source: Internet
Author: User

Views (view)
    • Basic usage
      • Passing data to a view
      • Share data in multiple views
    • View Components

#基本用法

The view contains the HTML code provided by your application, and provides a simple way to separate the logic on the controller and page rendering. The view is saved resources/views inside the folder.

A simple view might look like this:

<!-- 视图被保存在 resources/views/greeting.php -->

This view can be passed to the user's browser using the following code:

Route::get(‘/‘, function(){ return view(‘greeting‘, [‘name‘ => ‘James‘]);});

As you can see, the view first parameter of the helper method corresponds to the resources/views name of the view file within the folder; view the second parameter passed to the helper method is an array of data that can be used in the view.

Of course, view files can also be stored resources/views within subfolders. For example, if your view file is saved in resources/views/admin/profile.php , you can use the following code to return:

return view(‘admin.profile‘, $data);
Passing data to a view
// 使用传统的方法$view = view(‘greeting‘)->with(‘name‘, ‘Victoria‘);// 使用魔术方法$view = view(‘greeting‘)->withName(‘Victoria‘);

In the example code above, the view will be used $name to get the data with a value of Victoria .

If you want, there's another way to directly view pass an array directly to the second parameter of the helper method:

$view = view(‘greetings‘, $data);

If you use the method above to make data, it $data must be the array data of the key/value corresponding, so in the view, you can use the corresponding key to get the value, such as: {{ $key }} will get $data[‘key‘] the corresponding data.

Share data to all views

Sometimes you may need to share some data for all of your views, you have many choices: view helper methods, Illuminate\Contracts\View\Factory contracts (contract), and wildcard characters in view composer.

Here is an view example of an auxiliary method:

view()->share(‘data‘, [1, 2, 3]);

You can also use view the facade:

View::share(‘data‘, [1, 2, 3]);

Usually you should use the method within the service provider's boot method share . You can choose to add AppServiceProvider or create a separate service provider to accommodate the code.

Note: When the view helper method does not bring in any parameter calls, it returns the implementation of a Illuminate\Contracts\View\Factory contract (contract) (Implementation).

Confirm whether the view exists

If you need to confirm that the view exists, use the exists method:

if (view()->exists(‘emails.customer‘)){    //}
Generate a view from a file path

You can generate a view from a full file path:

return view()->file($pathToFile, $data);

View Components

A view component is a closure or class method that is called before the view is rendered. If you want to bind data each time a certain view is rendered, the view component can organize such program logic in the same place.

Defining a View Component

Let's organize our view components within the service provider. The example below will use View facade to Illuminate\Contracts\View\Factory achieve the underlying contract:

<?php namespace App\Providers;use View;use Illuminate\Support\ServiceProvider;class ComposerServiceProvider extends ServiceProvider {    /**     * Register bindings in the container.     *     * @return void     */    public function boot()    {        // 使用类来指定视图组件        View::composer(‘profile‘, ‘App\Http\ViewComposers\ProfileComposer‘);        // 使用闭包来指定视图组件        View::composer(‘dashboard‘, function($view)        {        });    }    /**     * Register the service provider.     *     * @return void     */    public function register()    {        //    }}

remark: Laravel does not have a default folder to place view components in the form of classes. You are free to put them where you want them. For example, you can put it App\Http\ViewComposers inside a folder.

Remember to add this service provider to the config/app.php array of configuration files providers .

Now that we have registered the view component, it will be executed every time the profile view is rendered [email protected] . Now let's look at how this class is defined:

<?php namespace App\Http\ViewComposers;use Illuminate\Contracts\View\View;use Illuminate\Users\Repository as UserRepository;class ProfileComposer {    /**     * The user repository implementation.     *     * @var UserRepository     */    protected $users;    /**     * Create a new profile composer.     *     * @param  UserRepository  $users     * @return void     */    public function __construct(UserRepository $users)    {        // service container 会自动解析所需的参数        $this->users = $users;    }    /**     * Bind data to the view.     *     * @param  View  $view     * @return void     */    public function compose(View $view)    {        $view->with(‘count‘, $this->users->count());    }}

Before the view is rendered, the method of the view component is compose called, and an instance is passed in Illuminate\Contracts\View\View . You can use with methods to bind data to view .

Note: All view components are parsed by the service container, so you need to limit any dependent parameters you need in the view component's constructor type.

Using wildcard characters within a view component

ViewThe composer method can be accepted * as a wildcard, so you can attach the following to all views composer :

View::composer(‘*‘, function($view){    //});
Attach view components to multiple views at the same time

You can also attach the same view component for multiple views at the same time:

View::composer([‘profile‘, ‘dashboard‘], ‘App\Http\ViewComposers\MyViewComposer‘);
Defining multiple View Components

You can use composers methods to define a group of view components at the same time:

View::composers([    ‘App\Http\ViewComposers\AdminComposer‘ => [‘admin.index‘, ‘admin.profile‘],    ‘App\Http\ViewComposers\UserComposer‘ => ‘user‘,    ‘App\Http\ViewComposers\ProductComposer‘ => ‘product‘]);
View Creator

The View creator is almost the same as the view component, except that the creator of the view executes it immediately after the view is initialized. To register a creator, simply use the creator method:

View::creator(‘profile‘, ‘App\Http\ViewCreators\ProfileCreator‘);

Laravel5.1 Learning Note 7 view

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.