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.
source share