Подтвердить что ты не робот

PHP-код внутри шаблона Blade Laravel 5

Мне нужно поместить некоторый PHP-код в шаблон Laravel 5 Blade Template. Как ниже

@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

Какова фактическая процедура размещения PHP-кода внутри шаблона Blade Blade?

4b9b3361

Ответ 1

Согласно документации, в Laravel 5.2 и новее вы можете использовать следующий код:

@php
{{-- php code here --}}
@endphp

В качестве альтернативы вы можете расширить движок Blade templating, как описано здесь.

Если ни одно из приведенных выше решений не подходит, вы застряли в ответах @Armen и @Gonzalo

Ответ 2

Просто откройте и закройте теги php: <?php $style = '...'; ?>

Ответ 3

Рецепты Laravel предлагают простой, но эффективный способ сделать это, не включая теги php

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

{{- -}} работает как комментарий к лезвию/и/возвращает эффект комментария в результате

<?php $var = 'test' ?>

Проблема в том, что она длиннее, чем теги php: - (

Ответ 4

Следующий новый 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);
    }

}

?>