2015-06-27 34 views
12

我必須在Laravel 5刀片模板裏放置一些PHP代碼。像下面一樣Laravel 5刀片模板裏面的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刀片模板內的PHP代碼?

回答

8

只需打開和關閉PHP標籤:<?php $style = '...'; ?>

0

以下新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); 
    } 

} 

?> 
2

Laravel食譜提出一個簡單而有效的方式做到這一點,而不包括PHP標籤

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

{{ - - }}工程作爲刀片評論/和/恢復評論對

<?php $var = 'test' ?> 

所得的問題是,比包括更長的效果PHP標籤:-(

24

documentation,在Laravel 5.2及更高版本,你可以使用下面的代碼:

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

或者,因爲它描述here可以延長刀片模板引擎。

如果上述兩種解決方案都不合適,您將被拒絕@Armen和@Gonzalo給出的答案