Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel extend blade and pass array as parameter

I have searched a lot regarding this topic and didn't find much on the web so I started to research and create a complete article on this topic but I am unable to understand some things here, making basic custom tags in blade is easy like

@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

At present I am 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 three parameters and get content between end and start tag? Your help is appreciated. Thanks for your responses.

like image 229
Imran Iqbal Avatar asked Jul 08 '14 10:07

Imran Iqbal


1 Answers

This question is more than 1 year old now, but I'm sharing a solution if somebody else need it in the future.

Using the first example:

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

It's possible to 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;
});

Explaining the code:

  1. We extend the pattern to match the content between @cache and @endcache. Note the use of s modifier in the expression. This way we can match multiple lines with a . (dot).
  2. Check if the expression matched something using count($matches) and assign it to $content.
  3. Finally we replace the blade tag by the function call. Since our pattern already matches the open and close tags and all content between them, we don't need to worry about replace the closing tag or something else.

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

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

Based on the example above you'll have:

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

I'm also simply returning the content in my example, but you can do something more interesting there.

like image 156
Gustavo Straube Avatar answered Sep 30 '22 19:09

Gustavo Straube