Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `HtmlString` used for in Laravel?

Tags:

php

laravel

This class: 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();
    }
}

use:

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

It does nothing but "construct" an string and return the string itself!

Can anyone explain it? Thanks a lot :)

like image 340
wbsnail Avatar asked Feb 18 '17 19:02

wbsnail


Video Answer


1 Answers

Since it implements an interface (Htmlable), other methods can potentially check whether a string it's been given should be treated as HTML or not.

It's not used that much, but for instance in 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);
    }
}

Here, you can see that if the $value adhers to the Htmlable interface, it can be printed right away. Otherwise, the string is printed in escaped form.

like image 64
Joel Hinz Avatar answered Oct 07 '22 21:10

Joel Hinz