【问题标题】:What is the difference between Laravel setEscapedContentTags and setContentTags?Laravel setEscapedContentTags 和 setContentTags 有什么区别?
【发布时间】:2015-05-18 09:53:56
【问题描述】:

为了更好地理解 Laravel 标签设置的工作原理,我尝试了以下方法:

Blade::setContentTags('<x', 'x>');
Blade::setEscapedContentTags('<y', 'y>');
Blade::setRawTags('<z', 'z>');

在我的控制器构造函数中。

在 Blade 视图中,我添加了

<div>
  <x 'test' x>
  <y 'test' y>
  <z 'test' z>
</div>

我清理了 storage/framework/views 文件夹并重新加载了页面。

结果,在编译视图中我得到了

<div>
    <?php echo e('test'); ?>

    <?php echo e('test'); ?>

    <?php echo 'test'; ?>

</div>  

如您所见,为使用 setContentTags 和 setEscapedContentTags 指定的标签编译的代码看起来是一样的。那么为什么我们需要这两个选项呢?

【问题讨论】:

    标签: php templates laravel-5


    【解决方案1】:

    这是出于安全考虑。 默认情况下,Blade 将为具有常规标签和转义标签的内容返回相同的结果。 BladeCompiler 类具有受保护的属性 $echoFormat,其值为 e(%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);
    }
    

    e 函数也会在使用 转义标签 编译内容时调用(在您的情况下是“y”)

    您也可以更改格式:

    /**
     * Set the echo format to be used by the compiler.
     *
     * @param  string  $format
     * @return void
     */
    public function setEchoFormat($format)
    {
        $this->echoFormat = $format;
    }
    

    使用默认设置Blade,如果您在文本前面加上@ 符号,则regularescaped tags 的内容将返回不同的结果。

    查看参数

    ['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>@&lt;script&gt;alert(&#039;name&#039;)&lt;/script&gt;</div>
    
    <div>{{"<a>Plain text</a>"}}</div>
    <div>@&lt;a&gt;Plain text&lt;/a&gt;</div>
    

    【讨论】:

      猜你喜欢
      • 2018-02-13
      • 2015-06-26
      • 2015-07-03
      • 1970-01-01
      • 2019-03-27
      • 2018-01-09
      • 2016-10-01
      • 2017-10-22
      • 2017-11-08
      相关资源
      最近更新 更多