在Laravel 5的Blade模板中包含PHP代码

56

我需要在Laravel 5的Blade模板中放置一些PHP代码,如下所示:

@foreach ($farmer->tasks as $task)
    @if ($task->pivot->due_at) < date(now))
        $style = 'alert alert-danger';
    @elseif ($task->pivot->due_at) > date(now))
        $style = 'alert alert-success';
    @else
        $style = '';
    @endif
@endforeach

如何在Laravel 5的Blade模板中嵌入PHP代码?

5个回答

137
根据文档,在 Laravel 5.2 及更高版本中,您可以使用以下代码:
@php
{{-- PHP code here --}}
@endphp

或者,您可以按照此处所述的方式扩展 Blade 模板引擎。

如果以上两种解决方案都不适合您,那么您只能使用 ArmenGonzalo 给出的答案。


3
实际上,我想了解@php<?php之间的区别……我的意思是,可能有理由添加这些指令。 - Advena
据我所知,在写代码时使用@php<?php没有区别。我曾经与一些更喜欢使用<?php而不是@php的人一起工作,他们的主要原因是因为他们在原始PHP中已经使用了一段时间,所以更习惯于这种方式。但通常在代码审查期间,我会将它们改回@php,因为这是我喜欢的写法。在Laravel文档中要求使用@php。我猜这是为了保持Blade语法的一致性。 - I. Antonov
1
@I.Antonov,在您公司的样式指南中应该定义使用@php<?php之一。根据最后一个接触文件的人来回切换样式并不是代码审查的目的。 - Peilonrayz
@Peilonrayz 对啊,我试着让他们这样做。但最初他们不感兴趣,因为他们“没时间”。相反,我们被指派在审核和推送终稿时进行更改。只是分享一种情况。而我现在已经不在那里工作了。 - I. Antonov

23

只需打开和关闭PHP标记:

<?php $style = '...'; ?>

3
似乎对于 Laravel 4,唯一的解决方案是因为不支持 @php 指令。 - Aleksandar Belic

11

在现代 Laravel(6/7)中,您应该这样做:

@php
   yourphpcode();
@endphp

7

Laravel的“recipes”提供了一种简单而有效的方法,可以在不包含PHP标记的情况下完成它:

{{--*/ $var = 'test' /*--}}

{{-- --}}作为Blade中的注释,用于注释掉代码块。而/和/则是取消注释效果。

<?php $var = 'test' ?>

问题在于它的长度超出了包括 PHP 标记的长度 :-(

我刚刚浪费了一个小时,纠结于一个被注释掉的变量是如何获得它的值的。谢谢。 - Slavic

5
以下新的 NewBladeCompiler 将使用 @{ }} 来接受所有 PHP 代码,如变量赋值、类声明等。
例如,@{ $variable = 0; }} 将被编译为 <?php $variable=0; ?>
<?php

    use Illuminate\View\Compilers\BladeCompiler;

    class NewBladeCompiler extends BladeCompiler
    {

        /**
         * Get the echo methods in the proper order for compilation.
         *
         * @return array
         */
        function getEchoMethods()
        {
            $methods = [
                'compileRawEchos'     => strlen(stripcslashes($this->rawTags[0])),
                'compileEscapedEchos' => strlen(stripcslashes($this->escapedTags[0])),
                'compileRegularEchos' => strlen(stripcslashes($this->contentTags[0])),
                'compilePhpEchos'     => strlen(stripcslashes("@{"))
            ];

            uksort($methods, function ($method1, $method2) use ($methods) {

                // Ensure the longest tags are processed first
                if($methods[$method1] > $methods[$method2])
                {
                    return -1;
                }
                if($methods[$method1] < $methods[$method2])
                {
                    return 1;
                }

                // Otherwise give preference to raw tags (assuming they've overridden)
                if($method1 === 'compilePhpEchos')
                {
                    return -1;
                }
                if($method2 === 'compilePhpEchos')
                {
                    return 1;
                }
                if($method1 === 'compileRawEchos')
                {
                    return -1;
                }
                if($method2 === 'compileRawEchos')
                {
                    return 1;
                }
                if($method1 === 'compileEscapedEchos')
                {
                    return -1;
                }
                if($method2 === 'compileEscapedEchos')
                {
                    return 1;
                }
            });

            return $methods;
        }

        function compilePhpEchos( $value )
        {
            $pattern  = sprintf('/(@)?%s\s*(.+?)\s*%s(\r?\n)?/s', "@{", "}}");
            $callback = function ($matches) {
                $whitespace = empty($matches[3]) ? '' : $matches[3] . $matches[3];
                return $matches[1] ? substr($matches[0], 1) : '<?php ' . $matches[2] . ' ?>' . $whitespace;
            };
            return preg_replace_callback($pattern, $callback, $value);
        }

    }

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接