在Laravel中使用什么是"HtmlString"?

wbs*_*wjc 8 php 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().'">');
    }

它只会"构造"一个​​字符串并返回字符串本身!

有人能解释一下吗?非常感谢 :)

Joe*_*inz 9

由于它实现了一个接口 ( 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到,如果$value贴在Htmlable界面上,则可以立即打印。否则,字符串以转义形式打印。


小智 -3

如果我理解得好,你想在文件中使用它.blade.php吗?使用

{{csrf_field()}}
Run Code Online (Sandbox Code Playgroud)