【问题标题】:Laravel access blade variable in helperLaravel 在助手中访问刀片变量
【发布时间】:2018-09-30 17:08:08
【问题描述】:

我有一个公共变量$publisher 共享给所有视图:

$view->with('publisher', $publisher);

示例:我想检查这个发布者是否被命名为“main”并且状态为“active”,因此我必须在刀片中编写 if 语句,如下所示:

@if ($publisher->name == 'main' && $publisher->status == 'active')
    // Code here
@endif

它为所有刀片文件复制,因此我在app/Helpers/general.php 创建了一个自定义帮助文件,将其命名为isMainPublisher($publisher)

function isMainPublisher($publisher) 
{
    return ($publisher->name == 'main' && $publisher->status == 'active') ? true: false;
}

刀片if语句将改为:

@if (isMainPublisher($publisher))
    // Code here
@endif

我正在考虑将刀片代码缩短为:

@if (isMainPublisher())
    // Code here
@endif

但是app/Helpers/general.php 不会访问blade 变量$publisher,无论如何或实际上没有办法访问helper 中的blade 变量?谢谢。

【问题讨论】:

  • 不是一个直接的答案,但是在 Publisher 对象上使用 isMain() 方法不是更有意义吗?并称之为$publisher->isMain()。它更具表现力。除此之外,您可以使用变量 $isMainPublisher 而不是助手并与所有视图共享它。
  • @AH.Pooladvand 他们为什么要这样做?如果这与模型有关,我相当肯定它确实如此,那么将方法添加到模型中会更有意义。实际上,如果 OP 需要在其他任何地方再次使用该方法,他就可以将它放在模型上,而无需重新编写它。永远记住 DRY 原则!
  • @Derek 我完全同意你的回答,但他想要@if (isMainPublisher()) 逻辑,所以我试图给他他想要的东西。
  • 那是不可行的。您如何获得isMainPublisher() 中的$publisher 变量?
  • @Momo 我同意 Derek 的回答。

标签: laravel laravel-5.4 blade


【解决方案1】:

基本上,除了在帮助程序类的内部变量上设置发布者名称之外,isMainPublisher($publisher) 是您的最佳选择,而且它比其他选项更惯用。

为了让isMainPublisher() 工作(可能),您必须使用一个 hacky 全局声明,即使那样,它也可能无法工作,因为它对类不可用

或者,您可以将帮助器作为方法添加到模型中:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Publisher extends Model
{
    // Your new helper method
    public function isMain()
    {
        // some logic to determine if the publisher is main
        return ($this->name == "main" || $this->name == "blah"); 
    }
}

...然后这样称呼它:

$publisher->isMain();

在我看来,这是最好的选择,就像你说的那样。

我希望这会有所帮助!

【讨论】:

  • 我同意这是一个更好的选择。
  • 感谢您的回答
  • Mike 谢谢@Momo 没问题,你能接受它作为答案吗
猜你喜欢
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2019-01-20
  • 2019-02-19
  • 2020-11-16
  • 2021-12-23
  • 2014-12-08
相关资源
最近更新 更多