Ra mắt hai series mới cực hot Trí tuệ nhân tạo A đến ZPython công cụ không thể thiếu khi nghiên cứu Data science, Machine learning.

Laravel HTML package viết mã HTML dễ dàng

Trong dự án, các tài nguyên như ảnh, các file css, javascript, font... được đặt trong thư mục public, để tổ chức tốt hơn chúng ta sẽ tạo ra các thư mục css, js, font chứa các loại file tương ứng. Khi tham chiếu đến các tài nguyên chúng ta có thể sử dụng ngôn ngữ HTML tiêu chuẩn hoặc có một tùy chọn nữa là sử dụng mã giả của gói Laravel HTML, ví dụ:

<img src="/images/logo.png" alt="All Laravel Logo" />

{!! HTML::image('images/logo.png', 'All Laravel Logo) !!}

Cài đặt gói Laravel HTML package

Đến thư mục gốc của dự án và sử dụng lệnh composer require để cài đặt gói Laravel HTML (tên chính xác là LaravelCollective). Ở các phiên bản Laravel 4.x gói này được cài đặt sẵn trong Laravel nhưng đến phiên bản Laravel 5.x gói này bị loại bỏ, muốn sử dụng phải cài đặt thêm.

c:\xampp\htdocs\laravel-test>composer require laravelcollective/html
Using version ^5.4 for laravelcollective/html
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing laravelcollective/html (v5.4.1): Downloading (100%)
Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled services file has been removed.

Tiếp theo chúng ta sẽ thêm gói này vào các cấu hình của Laravel, mở file config/app.php thêm dòng dưới đây vào phần providers và aliases.

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        ...
        Collective\Html\HtmlServiceProvider::class,
],
'aliases' => [
        ...
        'Form'      => Collective\Html\FormFacade::class,
        'Html'      => Collective\Html\HtmlFacade::class,
],

Ok, phần cài đặt gói LaravelCollective đã được cài đặt ## Chèn ảnh, css, javascript vào blade qua Laravel HTML

Cú pháp để chèn ảnh

<img src="/images/logo.png" alt="All Laravel Logo" />

{!! HTML::image('images/logo.png', 'All Laravel Logo') !!}

Cú pháp chèn file css

<link rel="stylesheet" href="/css/app.min.css">

{!! HTML::style('css/app.min.css') !!}

Cú pháp chèn file javascript

<script src="/javascript/jquery-1.10.1.min.js"></script>

{!! HTML::script('javascript/jquery-1.10.1.min.js') !!}

Xây dựng form nhập liệu bằng Laravel HTML

Chúng ta xem một form dạng HTML

<form action = "/contact" method = "post">
   <input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>">
   <table>
      <tr>
         <td>Họ và tên</td>
         <td><input type = "text" name = "name" <?php if(isset($name)) echo 'value = "' . $name . '"'?>/></td>
      </tr>

      <tr>
         <td>Địa chỉ email</td>
         <td><input type = "text" name = "email" <?php if(isset($email)) echo 'value = "' . $email . '"'?>/></td>
      </tr>

      <tr>
         <td>Tiêu đề</td>
         <td><input type = "text" name = "title" /></td>
      </tr>

      <tr>
         <td>Nội dung</td>
         <td>
            <textarea name="message" rows="5"></textarea>
         </td>
      </tr>

      <tr>
         <td colspan = "2" align = "center">
            <input type = "submit" value = "Gửi" />
         </td>
      </tr>
   </table>
</form>

Các lệnh liên quan đến mở Form

{!! Form::open(array('url' => 'foo/bar')) !!}
    //
{!! Form::close() !!}

Sử dụng {!! !!} thay cho {{ }} để in ra mã HTML không bị chuyển đổi, xem bài Laravel Blade phần 1 để hiểu hơn cách sử dụng các cách in biến trong Blade. Mặc định khi mở form action sẽ là POST, tuy nhiên chúng ta có thể đẩy dữ liệu lên server theo dạng khác bằng cách thêm tham số (hỗ trợ các phương thức POST, GET, DELETE và PUT):

{!! Form::open(array('url' => 'foo/bar', 'method' => 'put')) !!}

Có rất nhiều các dạng thẻ mở Form khác nhau, mở Form và trỏ đến một route hoặc một phương thức trong Controller

{!! Form::open(array('route' => 'route.name')) !!}

{!! Form::open(array('action' => 'Controller@method')) !!}

Có thể truyền tham số vào cách mở Form này:

{!! Form::open(array('route' => array('route.name', $user->id))) !!}

{!! Form::open(array('action' => array('Controller@method', $user->id))) !!}

Với các Form có upload file, thêm tham số file:

{!! Form::open(array('url' => 'foo/bar', 'files' => true)) !!}

CSRF Protect

Laravel cung cấp một phương thức để bảo vệ ứng dụng của bạn khỏi các yêu cầu từ ngoài dạng tấn công cross-site, hệ thống tự động sinh ra ngẫu nhiên một token và đặt trong session, khi bạn sử dụng Form::open với POST, PUT hoặc DELETE thì CSRF token sẽ được tự động thêm vào dạng field ẩn. Nếu bạn sinh mã HTML thuần túy cho trường CSRF, có thể sử dụng phương thức token.

{!! Form::token() !!}

Các dạng thẻ trong Form

Tạo một nhãn (tương đương thẻ <label></label>)

{!! Form::label('email', 'Địa chỉ Email') !!}

Muốn thêm class vào cho thẻ này truyền thêm tham số:

{!! Form::label('email', 'Địa chỉ Email', array('class' => 'label-success')) !!}

Tạo trường nhập liệu text, email, password, upload file

{!! Form::text($name, $value = null, $attributes = array()) !!}
{!! Form::textarea($name, $value, $attributes = array()) !!}
{!! Form::email($name, $value = null, $attributes = array()) !!}
{!! Form::password($name) !!}
{!! Form::file($name, $attributes = array()) !!}

Tạo checkbox và radio button

{!! Form::checkbox('$name', '$value', true) !!}

{!! Form::radio('$name', '$value', true) !!}

Trường nhập liệu ngày tháng

{!! Form::date('post_date', \Carbon\Carbon::now()) !!}

Tạo Dropdown list lựa chọn giá trị

{!! Form::select('size', array('1' => 'Laravel', '2' => 'Symfony', '3' => 'Yii'), '1') !!}

Tạo nút Submit

{!! Form::submit('Gửi tin nhắn') !!}

Quay lại ví dụ về Form HTML thuần túy ban đầu có thể viết lại theo mã Laravel HTML như sau:

{!! Form::open(array('url' => '/contact')) !!}
   <table>
      <tr>
         <td>{!! Form::label('name', 'Họ và tên') !!}</td>
         <td>{!! Form::text('name', isset($name)?$name:'') !!}</td>
      </tr>

      <tr>
         <td>{!! Form::label('email', 'Địa chỉ Email') !!}</td>
         <td>{!! Form::email('email', isset($email)?$email:'') !!}</td>
      </tr>

      <tr>
         <td>{!! Form::label('title', 'Tiêu đề') !!}</td>
         <td>{!! Form::text('title', '') !!}</td>
      </tr>

      <tr>
         <td>{!! Form::label('content', 'Nội dung') !!}</td>
         <td>
            {!! Form::textarea('title', '', array('rows' => '3', 'cols' => '100')) !!}
         </td>
      </tr>

      <tr>
         <td colspan = "2" align = "center">
            {!! Form::submit('Gửi') !!}
         </td>
      </tr>
   </table>
{!! Form::close() !!}

Ok, chúng ta cập nhật code này vào file contact.blade.php trong resources/views/fontend và thử lại đường dẫn http://laravel.dev/contact.

Form contact sử dụng Laravel HTML

Tiện đây, chúng ta điều chỉnh lại view contact kế thừa blade template default, kết hợp luôn cùng với style của Bootstrap:

@extends('layouts.default')

@section('title', 'All Laravel - Liên hệ với chúng tôi')

@section('content')
   {!! Form::open(array('url' => '/contact', 'class' => 'form-horizontal')) !!}
      <div class="form-group">
         {!! Form::label('name', 'Họ và tên', array('class' => 'col-sm-2 control-label')) !!}
         <div class="col-sm-10">
            {!! Form::text('name', isset($name)?$name:'', array('class' => 'form-control', 'placeholder' => 'Nhập họ tên đầy đủ')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('email', 'Địa chỉ email', array('class' => 'col-sm-2 control-label')) !!}
         <div class="col-sm-10">
            {!! Form::email('email', isset($email)?$email:'', array('class' => 'form-control', 'placeholder' => 'Địa chỉ email thật để nhận phản hồi')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('title', 'Tiêu đề', array('class' => 'col-sm-2 control-label')) !!}
         <div class="col-sm-10">
            {!! Form::text('title', '', array('class' => 'form-control', 'placeholder' => 'Tiêu đề tin nhắn')) !!}
         </div>
      </div>

      <div class="form-group">
         {!! Form::label('content', 'Nội dung liên hệ', array('class' => 'col-sm-2 control-label')) !!}
         <div class="col-sm-10">
            {!! Form::textarea('content', '', array('class' => 'form-control', 'placeholder' => 'Nội dung không quá 200 từ', 'rows' => '3')) !!}
         </div>
      </div>

      <div class="form-group">
         <div class="col-sm-offset-2 col-sm-10">
            {!! Form::submit('Gửi tin nhắn', array('class' => 'btn btn-success')) !!}
         </div>
      </div>
   {!! Form::close() !!}
@endsection

Kết quả khi vào http://laravel.dev/contact trông đẹp hơn hẳn

Form liên hệ sử dụng Laravel HTML kết hợp Bootstrap

Tại sao sử dụng Laravel HTML

Khi sử dụng Laravel HTML code trông dễ nhìn hơn, và truyền các tham số vào các thành phần dễ dàng hơn rất nhiều. Với mở Form chúng ta chỉ cần Form::open là đã có sẵn trường ẩn chứa CSRF token. Với các trường kiểu dropdown select, khi truyền tham số vào nếu sử dụng HTML thuần túy chúng ta phải sử dụng vòng lặp. Ví dụ dưới đây sẽ cho bạn thấy vì sao sử dụng Laravel HTML:

@php
   $php_framework_arr = ["L" => "Laravel", "S" => "Symfony", "Y" => "Yii", "C" => "CodeIgniter"];
@endphp
<select name="framework">
   @foreach($php_framework_arr as $frm)
      <option>{{ $frm }}</option>
   @endforeach
</select>

Với thẻ select của HTML như trên chúng ta có thể đơn giản hơn như sau:

@php
   $php_framework_arr = ["L" => "Laravel", "S" => "Symfony", "Y" => "Yii", "C" => "CodeIgniter"];
@endphp
{!! Form::select('framework', $php_framework_arr) !!}

Còn rất nhiều các ví dụ khác, bạn hãy từ từ hiểu dần khi tham gia một dự án cụ thể nhé.


CÁC BÀI VIẾT KHÁC

FirebirD

Đam mê Toán học, Lập trình. Sở thích chia sẻ kiến thức, Phim hài, Bóng đá, Cà phê sáng với bạn bè.

Laravel Blade template module hóa trong thiết kế giao diện - Phần 2

Tích hợp Bootstrap vào Laravel

9 Bình luận trong "Laravel HTML package viết mã HTML dễ dàng"

  1. 6 years ago

    Phản hồi
    Hi Admin. Mình đã làm theo các bước trên nhưng vẫn không dùng được laravelcollective
    1. FirebirD

      6 years ago

      Phản hồi
      Bạn đang vướng ở bước mấy, khi chạy nó có báo lỗi cụ thể gì không?
    2. Nam

      5 years ago

      Phản hồi
      {!! HTML::style('css/bootstrap.min.css') !!} to {!! Html::style('css/bootstrap.min.css') !!} là hoạt động bt nhé!
  2. HYoeng

    5 years ago

    Phản hồi
    Hi Admin, Mình chạy trên cmd nó toàn báo như thế này !! ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update Writing lock file Generating autoload files > Illuminate\Foundation\ComposerScripts::postUpdate > php artisan optimize Generating optimized class loader The compiled services file has been removed.
  3. FirebirD

    5 years ago

    Phản hồi
    Nothing to install or update. Tức là phiên bản các package trong composer.json đã được cập nhật mới nhất với các thiết lập về phiên bản và hiện trạng các package ở trên mạng. Bạn gặp vấn đề cụ thể gì khi chạy câu lệnh này hoặc tình huống cụ thể của bạn là gì? Bạn mô tả kĩ hơn nhé
  4. Nga

    4 years ago

    Phản hồi
    Em viết câu lệnh composer require laravelcollective/html thì ra thế này ạ,em đã update lại composer r mà vẫn thế này PS C:\xampp\htdocs\lrv> composer require laravelcollective/html Using version ^5.8 for laravelcollective/html ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - Conclusion: remove laravel/framework v5.7.28 - Conclusion: don't install laravel/framework v5.7.28 - laravelcollective/html 5.8.x-dev requires illuminate/view 5.8.* -> satisfiable by illuminate/view[5.8.x-dev, v5.8.0, v5.8.2, v5.8.3]. - laravelcollective/html v5.8.0 requires illuminate/view 5.8.* -> satisfiable by illuminate/view[5.8.x-dev, v5.8.0, v5.8.2, v5.8.3]. - don't install illuminate/view 5.8.x-dev|don't install laravel/framework v5.7.28 - don't install illuminate/view v5.8.0|don't install laravel/framework v5.7.28 - don't install illuminate/view v5.8.2|don't install laravel/framework v5.7.28 - don't install illuminate/view v5.8.3|don't install laravel/framework v5.7.28 - Installation request for laravel/framework (locked at v5.7.28, required as 5.7.*) -> satisfiable by laravel/framework[v5.7.28]. - Installation request for laravelcollective/html ^5.8 -> satisfiable by laravelcollective/html[5.8.x-dev, v5.8.0]. Installation failed, reverting ./composer.json to its original content.
  5. Bình

    3 years ago

    Phản hồi

    Chạy được nhưng không hiểu gì

  6. nguyen

    3 years ago

    Phản hồi

    mình nghĩ Ad nên giới thiệu sơ qua sau đó làm theo mô hình một project nhỏ hoàn chình chi tiết, như z thì khá khó hiểu ? thank !

  7. Tiến

    3 years ago

    Phản hồi

    Laravel 6.0 mình chỉ cần dùng lệnh : [ composer require laravelcollective/html ] là xong, khỏi thêm trong file app.php. Với {!! Html:: !!} thay vì {!! HTML:: !!}. Cái này làm em mất cả tiếng để mò ra ^^

Thêm bình luận