2017-02-18 71 views
4

這個類:HtmlString在Laravel中使用了什麼`HtmlString?

 
<?php 

namespace Illuminate\Support; 

use Illuminate\Contracts\Support\Htmlable; 

class HtmlString implements Htmlable 
{ 
    /** 
    * The HTML string. 
    * 
    * @var string 
    */ 
    protected $html; 

    /** 
    * Create a new HTML string instance. 
    * 
    * @param string $html 
    * @return void 
    */ 
    public function __construct($html) 
    { 
     $this->html = $html; 
    } 

    /** 
    * Get the HTML string. 
    * 
    * @return string 
    */ 
    public function toHtml() 
    { 
     return $this->html; 
    } 

    /** 
    * Get the HTML string. 
    * 
    * @return string 
    */ 
    public function __toString() 
    { 
     return $this->toHtml(); 
    } 
}

使用:

 function csrf_field() 
    { 
     return new HtmlString('<input type="hidden" name="_token" value="'.csrf_token().'">'); 
    }

它什麼都不做,而是 「建設」 的字符串,返回字符串本身!

任何人都可以解釋它嗎?非常感謝:)

回答

0

如果我理解不錯,你想在.blade.php文件中使用它? 使用

{{csrf_field()}} 
+0

當然,它就像你說的XD一樣使用,但是我很好奇它下面的HtmlString類,謝謝你的時間。 – zjuwujunchao

+0

注意'csrf_field()'返回'HtmlString',所以在刀片中你可以使用'{{...}}'而不是'{! '!!}'。不需要記住打印原始數據並確保它不會被轉義 – morph

2

由於它實現了一個接口(Htmlable),其他方法可以潛在地檢查它的被賦予的字符串是否應被視爲HTML或沒有。

它不是用來多,但例如在Illuminate/Support/helpers.php:519

if (! function_exists('e')) { 
    /** 
    * Escape HTML special characters in a string. 
    * 
    * @param \Illuminate\Contracts\Support\Htmlable|string $value 
    * @return string 
    */ 
    function e($value) 
    { 
     if ($value instanceof Htmlable) { 
      return $value->toHtml(); 
     } 

     return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false); 
    } 
} 

在這裏,你可以看到,如果$value adhers到Htmlable接口,它可以立即打印出來。否則,該字符串將以轉義形式打印。

相關問題