herrjeh42
herrjeh42

Reputation: 2793

Using Blade directives outside of templates

Laravel 5.1: I defined a few custom directives inside a BladeServiceProvider (example below). Now I would like to use them outside of a view template to format strings (I am writing an EXCEL file with PHPExcel in a custom ExportService class). Is it possible to reuse my directives?

 Blade::directive('appFormatDate', function($expression) {
        return "<?php
         if (!is_null($expression)) {
           echo date(\Config::get('custom.dateformat'), strtotime($expression));
         }
         else {
           echo '-';
         }
         ?>";
    });

Upvotes: 3

Views: 754

Answers (2)

user21100425
user21100425

Reputation: 11

You can use this:

use Illuminate\Support\Facades\Blade;


$timestamp = '2023-01-28 12:41:53';
Blade::render("@appFormatDate({$timestamp})");

Upvotes: 1

Thomas Kim
Thomas Kim

Reputation: 15941

The BladeCompiler has a compileString method, which allows you to use the Blade directives outside the views. :)

So, you can do things like this:

$timestamp = '2015-11-10 17:41:53';
$result = Blade::compileString('@appFormatDate($timestamp)');

Upvotes: 2

Related Questions