2015-06-27 35 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给出的答案