我有一个字符串返回到我的一个视图,像这样:

$text = '<p><strong>Lorem</strong> ipsum dolor <img src="images/test.jpg"></p>'

我试图用Blade显示它:

{{$text}}

但是,输出是一个原始字符串,而不是呈现的HTML。我如何显示HTML与刀片在Laravel?

PS. PHP echo()正确显示HTML。


当前回答

还有另一种方法。如果对象的目的是渲染html,您可以实现具有toHtml()方法的\Illuminate\Contracts\Support\Htmlable合约。

然后,您可以像这样从blade渲染该对象:{{$someObject}}(注意,不需要{!!!!}语法)。

此外,如果你想返回html属性,并且你知道它将是html,使用\Illuminate\Support\HtmlString类,如下所示:

public function getProductDescription()
{
    return new HtmlString($this->description);
}

然后像{{$product->getProductDescription()}}那样使用它。

当然,在页面上直接渲染原始html时要负责任。

其他回答

如果你有时使用Bootstrap折叠类{!!美元的文本! !} 不是为我工作,但{{html_entity_decode($text)}}是为我工作。

使用{! !美元的文本! !}来显示数据而不转义。只是要确保不要对来自用户且未被清理的数据执行此操作。

如果要转义数据使用

{{ $html }}

如果不想逃避数据使用

{!! $html !!}

但在laravel4之前你可以使用

{{ HTML::link('/auth/logout', 'Sign Out', array('class' => 'btn btn-default btn-flat')) }}

当谈到laravel5时

{!! HTML::link('/auth/logout', 'Sign Out', array('class' => 'btn btn-default btn-flat')) !!} 

您也可以使用PHP函数来实现这一点

{{ html_entity_decode($data) }}

通过PHP文档获取这个函数的参数

Html_entity_decode - php.net

还有另一种方法。如果对象的目的是渲染html,您可以实现具有toHtml()方法的\Illuminate\Contracts\Support\Htmlable合约。

然后,您可以像这样从blade渲染该对象:{{$someObject}}(注意,不需要{!!!!}语法)。

此外,如果你想返回html属性,并且你知道它将是html,使用\Illuminate\Support\HtmlString类,如下所示:

public function getProductDescription()
{
    return new HtmlString($this->description);
}

然后像{{$product->getProductDescription()}}那样使用它。

当然,在页面上直接渲染原始html时要负责任。

试试这个,它很有效:

@php 
   echo $text; 
@endphp