Laravel 5: Display HTML with Blade

后端 未结 20 2172
栀梦
栀梦 2020-11-22 16:21

I have a string returned to one of my views, like this:

$text = \'

Lorem ipsum dolor

相关标签:
20条回答
  • 2020-11-22 16:59

    To add further explanation, code inside Blade {{ }} statements are automatically passed through the htmlspecialchars() function that php provides. This function takes in a string and will find all reserved characters that HTML uses. Reserved characters are & < > and ". It will then replace these reserved characters with their HTML entity variant. Which are the following:

    |---------------------|------------------|
    |      Character      |       Entity     |
    |---------------------|------------------|
    |          &          |       &amp;      |
    |---------------------|------------------|
    |          <          |       &lt;       |
    |---------------------|------------------|
    |          >          |       &gt;       |
    |---------------------|------------------|
    |          "          |       &quot;     |
    |---------------------|------------------|
    

    For example, assume we have the following php statement:

    $hello = "<b>Hello</b>";
    

    Passed into blade as {{ $hello }} would yield the literal string you passed:

    <b>Hello</b>
    

    Under the hood, it would actually echo as &lt;b&gt;Hello&lt;b&gt

    If we wanted to bypass this and actually render it as a bold tag, we escape the htmlspecialchars() function by adding the escape syntax blade provides:

    {!! $hello !!}

    Note that we only use one curly brace.

    The output of the above would yield:

    Hello

    We could also utilise another handy function that php provides, which is the html_entity_decode() function. This will convert HTML entities to their respected HTML characters. Think of it as the reverse of htmlspecialchars()

    For example say we have the following php statement:

    $hello = "&lt;b&gt; Hello &lt;b&gt;";
    

    We could now add this function to our escaped blade statement:

    {!! html_entity_decode($hello) !!}
    

    This will take the HTML entity &lt; and parse it as HTML code <, not just a string.

    The same will apply with the greater than entity &gt;

    which would yield

    Hello

    The whole point of escaping in the first place is to avoid XSS attacks. So be very careful when using escape syntax, especially if users in your application are providing the HTML themselves, they could inject their own code as they please.

    0 讨论(0)
  • 2020-11-22 16:59

    I have been there and it was my fault. And very stupid one.

    if you forget .blade extension in the file name, that file doesn't understand blade but runs php code. You should use

    /resources/views/filename.blade.php
    

    instead of

    /resources/views/filename.php
    

    hope this helps some one

    0 讨论(0)
提交回复
热议问题