duannuochi3549 2018-03-08 05:25
浏览 29
已采纳

Laravel将变量偏离视图部分到主刀片或部分之间

I have a Laravel 5.5 app that uses view blades conventionally, nothing fancy. My blade is a long table of data and I split the group sections (item categories) into their own partials to manage the code better.

However, I can't find a way to pass variable data from the partials back to the main blade, or even between partials. The scope of the variables are bound within the partials and I need to show a page total that aggregates the sub-totals from the various partials (sections). I did try using

View::share('portfolio_total', 100);

in the AppServiceProvider, to no avail. I can set a value (like the 100 shown) that stays intact in the master blade, but doesn't pick up the value set in that variable in the partial. Changing the variable value inside the partial doesn't update the value available to the master blade. I've searched extensively for this and there are many examples of passing values into partials, but not back out.

Is there a Laravel trick for defining the equivalent of global variables that can have their value set in an included partial blade, and carry that value to another partial blade, or out to the master blade?

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsaxw4201 2018-03-08 08:32
    关注

    I can't find a way to pass variable data from the partials back to the main blade, or even between partials.

    That is because this is absolute bad practice. Hence the framework does not allow that (without abuses).

    Why?

    In the MVC world (which Laravel implements), views are responsible for displaying data.

    If you are computing anything in your views (partials or not), then it means you are giving Views the responsibility of the Controller and/or Model. Which is not good of course.

    Then what?

    Idea is to compute everything you need before using the views. Two options:

    • If your view/partial is used only by a single controller method, simply pass the data to the view as usual.
    • If your view/partial is used in various places, setup a ViewComposer which will be able to pass the computed data each time that partial is used.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀