P
P
photosho2016-01-30 01:18:14
Laravel
photosho, 2016-01-30 01:18:14

How to pass the value of a variable to your Blade directive?

Another question about the Blade templating engine. Again, as in the previous example, I display the date formatted using Carbon:

Blade::directive('date', function($expression) {
  return '<?php echo Carbon::ФУНКЦИЯ(' . $expression . '); ?>'
});

The directive should work like this:
@date($date)
The problem is the following. As far as I understand, the function returns a PHP code that is embedded instead of a directive on the page, after which it is already executed as a regular PHP insert ("$expression" in this example stores only the name of the variable - "$date", but not it meaning). But in order to use the function inside it, I need to connect the "Carbon" class to the module, and if it is not connected directly to the display that calls the directive, then a "Class not found" error occurs.
Now I solve the problem by simply adding "use" to the view, but this does not seem to be the right solution - the need to connect a class to each view along with calling the directive greatly reduces the effectiveness of this approach. Is it possible to somehow pass the value of the variable, and not its name, inside the directive declaration? Or is there another way out of this situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
photosho, 2016-01-30
@photosho

So far I've solved the problem with the following code:

Blade::directive('date', function($expression) {
  return '<?php echo Carbon\Carbon::ФУНКЦИЯ(' . $expression . '); ?>'
});

That is, I add the class path right before the output of the function. I would be grateful for comments on this method - whether it is correct / optimal and whether it will bring unnecessary problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question