如何扩展 Laravel Blade 功能并添加“中断”和“继续”支持

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21532488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:58:12  来源:igfitidea点击:

How to extend Laravel Blade functionality and add 'break' and 'continue' support

phplaravellaravel-4bladelaravel-routing

提问by Fractaliste

I would like to add @continueand @breakstatements for my Blade engine in order to control my loops.

我想为我的 Blade 引擎添加@continue@break语句以控制我的循环。

I've seen into the sources an extendfunction for the BladeEngine, and I've tried to use it in my routes.phpfile:

我已经在源代码中看到extend了 BladeEngine 的一个函数,并且我尝试在我的routes.php文件中使用它:

Blade::extend(function ($value) {
    $pattern = Blade::createMatcher('continue');
    return preg_replace($pattern, '<?php continue; ?>', $value);
});

One of my views:

我的观点之一:

@if (isset($meta['foo']) && !$meta['bar'])
    @continue
@else
    <li>{{$meta['pseudo']}}</li>
@endif

But the rendered HTML page shows me @continue.

但是呈现的 HTML 页面显示了我@continue

Any idea of how make it work?

知道如何使它工作吗?

回答by Gadoma

Did you clear cache/compiled view files after adding the provided piece of your code to routes.php? If not, try doing so as Blade will recompile the views only if changes are detected in them. So if you didn't clear the compiled views after adding the code, nothing changed in the rendered html.

在将提供的代码片段添加到 后,您是否清除了缓存/编译视图文件routes.php?如果没有,请尝试这样做,因为只有在检测到更改时,Blade 才会重新编译视图。因此,如果您在添加代码后没有清除已编译的视图,则渲染的 html 中没有任何变化。

If it's not the case, try using plain old regexp instead of the Blade::createMatcher, thisnice definition will provide you with both continue and break support in a oneliner.

如果不是这种情况,请尝试使用普通的旧正则表达式而不是 Blade::createMatcher,这个很好的定义将为您提供 oneliner 中的 continue 和 break 支持。

Blade::extend(function($value)
{
  return preg_replace('/(\s*)@(break|continue)(\s*)/', '<?php ; ?>', $value);
});

It should work even if placed in routes.php, although it's better to put it in a separate file (for example blade.php and include it in global.php). Anyway it must be loaded prior to the view being processed.

即使放在routes.php 中它也应该可以工作,尽管最好将它放在一个单独的文件中(例如blade.php 并将其包含在global.php 中)。无论如何,它必须在处理视图之前加载。