问题描述
为了更好地了解Laravel标记设置的工作原理,我尝试了以下操作:
To better understand how Laravel tag settings work, I tried the following:
Blade::setContentTags('<x', 'x>');
Blade::setEscapedContentTags('<y', 'y>');
Blade::setRawTags('<z', 'z>');
在我的控制器构造函数中.
in my controller constructor.
在刀片"视图中,我添加了
In Blade view, I added
<div>
<x 'test' x>
<y 'test' y>
<z 'test' z>
</div>
我清理了storage/framework/views文件夹并重新加载了页面.
I cleaned storage/framework/views folder and reloaded the page.
结果,在编译视图中,我得到了
As a result, in compiled view I got
<div>
<?php echo e('test'); ?>
<?php echo e('test'); ?>
<?php echo 'test'; ?>
</div>
如您所见,为使用setContentTags和setEscapedContentTags指定的标签编译的代码看起来相同.那么为什么我们都需要这两个选项?
推荐答案
这是一种安全原因.默认情况下,对于具有常规和转义标记的内容,Blade
将返回相等的结果. BladeCompiler
类具有值为e(%s)
的受保护属性$echoFormat
.当内容使用常规标签进行编译时(在您的情况下为'x'),将使用此属性.
It's kind of safety reason.By default, Blade
will return equal results for content with regular and escaped tags. BladeCompiler
class has protected property $echoFormat
with value e(%s)
. This property is used when content compiles with regular tags (in your case it's 'x').
/**
* The "regular" / legacy echo string format.
*
* @var string
*/
protected $echoFormat = 'e(%s)';
该属性用作功能e
/**
* Escape HTML entities in a string.
*
* @param string $value
* @return string
*/
function e($value)
{
return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
}
当内容使用转义标签(在您的情况下为'y')编译时,也会调用e
函数
The e
function is also called when content compiles with escaped tags (in your case it's 'y')
您还可以更改格式:
/**
* Set the echo format to be used by the compiler.
*
* @param string $format
* @return void
*/
public function setEchoFormat($format)
{
$this->echoFormat = $format;
}
在默认设置下,如果为文本加上@
符号前缀,Blade
将为带有regular
和escaped tags
的内容返回不同的结果.
With default settings Blade
will return different results for content with regular
and escaped tags
if you prefix your text with an @
symbol.
用于视图参数
['str' => "<script>alert('name')</script>"]
使用模板
<div>@{{ $str }}</div>
<div>@{{{ $str }}}</div>
<div>@{{"<a>Plain text</a>"}}</div>
<div>@{{{"<a>Plain text</a>"}}}</div>
结果将是
<div>{{ $str }}</div>
<div>@<script>alert('name')</script></div>
<div>{{"<a>Plain text</a>"}}</div>
<div>@<a>Plain text</a></div>
这篇关于Laravel setEscapedContentTags和setContentTags有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!