【问题标题】:Laravel: view data formattingLaravel:查看数据格式
【发布时间】:2015-12-31 20:07:43
【问题描述】:

问题:视图数据处理的所有逻辑应该放在哪里?

例子:

请求页面以显示帖子。视图 post.blade.php 具有不同的显示部分,具体取决于用户之前所做的事情(例如,竖起大拇指)。同一个视图的其他部分需要显示一些格式化的文本,结合各种模型字段,这是 Post 模型最初没有的。简而言之,一些主要的处理还在继续。

  1. 我想我可以在视图中完成所有这些操作,但是拥有一个没有任何 php 代码的视图不是更好吗?

  2. 我考虑过制作视图助手来解决这个问题。喜欢:

    class PostViewHelper {
    
        private $post;
    
        // decide which image to display
        public function getImage1() {
            // check if user has already given a thumbs up
        }  
        // decide how to display text
        public function getText1() {
        // construct a text using post fields
        }
    } 
    

    视图将使用此对象向用户显示数据。

  3. 还有这个视图作曲家的东西。也许这是拥有所有显示逻辑的地方? PostViewComposer 将完成所有工作并将格式化数据传递给视图。

你有什么建议?

【问题讨论】:

  • 我会在视图中做这一切。如果竖起大拇指使用此视图,如果不使用另一个。
  • 使用 all javascript 并从 ajax 获取数据也是一种选择。

标签: laravel view formatting data-processing


【解决方案1】:

您可以通过多种方式进行操作。把你的刀片模板弄干净是很好的。

你可以使用服务注入(https://laravel.com/docs/5.1/blade#service-injection)

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

或者您可以创建自己的刀片指令(https://laravel.com/docs/5.1/blade#extending-blade

以下示例创建一个@datetime($var) 指令,该指令格式化给定的$var

<?php

namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function($expression) {
            return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

此指令生成的最终 PHP 将是:

<?php echo with($var)->format('m/d/Y H:i'); ?>

或者你可以使用视图助手来做一些逻辑。喜欢https://laravel.com/docs/5.1/helpers#method-e 但你必须将它自动加载到你的composer.json 文件中,比如https://github.com/laravel/framework/blob/5.2/composer.json#L87

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2021-01-30
    • 2011-04-24
    相关资源
    最近更新 更多