Laravel extends the blade and skips the array as a parameter

I searched a lot for this topic and did not find much on the Internet, so I started to study and create a full article on this topic, but I can’t understand some things here, making basic user tags in the blade server easy as

@search @endsearch or @title('something') 

but what if I want to do something like below

 @cache('sidebar',10,[$silver,$gold,$platinum]) html tags come here @endcache 

I'm currently doing it like this

 @cache('sidebar_',10,function() use ($silver_sidebar,$gold_sidebar)) @endcache $pattern = Blade::createOpenMatcher('cache'); $replace = "<?php echo PageCache::cache$2 { ?>"; $view = preg_replace($pattern, $replace, $view); // Replace closing tag $view = str_replace('@endcache', '<?php }); ?>', $view); 

How to parse it to separate the three parameters and get the content between the end and start tags? Your help is appreciated. Thank you for your responses.

+6
source share
1 answer

This question has been around for more than 1 year, but I will use the solution if someone else needs it in the future.

Using the first example:

 @cache('sidebar', 10, [ $silver, $gold, $platinum ]) html tags come here @endcache 

You can do something like this:

 Blade::extend(function ($view) { $pattern = Blade::createOpenMatcher('cache'); $pattern = rtrim($pattern, '/') . '(.*?)@endcache/s'; $matches = []; preg_match($pattern, $view, $matches); $content = ''; if (count($matches) > 3) { $content = addslashes($matches[3]); } $replace = "<?php echo PageCache::cache$2, '{$content}'); ?>"; $view = preg_replace($pattern, $replace, $view); return $view; }); 

Code Explanation:

  • We are expanding the template to match the content between @cache and @endcache . Note the use of the s modifier in the expression. This way we can match multiple lines with . (point).
  • Check expression match with count($matches) and assign it to $content .
  • Finally, we replace the blade tag with a function call. Since our template already matches the open and close tags and everything in between, we don’t have to worry about replacing the closing tag or anything else.

This way you can get the content between the tags ( @cache and @endcache ) in your function:

 class PageCache { public static function cache($name, $num, $args, $content) { return stripslashes($content); } } 

According to the above example, you will have:

 $name = 'sidebar'; $num = 10; $args = [ $silver, $gold, $platinum ]; 

I also just return the contents in my example, but you can do something more interesting there.

+3
source

Source: https://habr.com/ru/post/971910/


All Articles