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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么