Composers. Pass data to the loop

Is it possible, in Sage 10, pass data to the loop as Sage9 controllers did with static functions?

Something like:

public static function catLinks()
{
    $cats = get_the_category();
    $output = "";
    foreach ($cats as $cat) {
        $output .= get_category_link($cat->slug);
    }
    return $output;
}

Then, from the view:

{{ App::catLinks() }}

I’ve accomplished this by breaking the looped content into a separate blade file, and then using a View Composer scoped to that new blade file.

I don’t have an example handy but does that help at all?

1 Like

Sounds more complicated than putting the data logic in the main template. Isn’t it?

I don’t think so, here’s how I do it:

resources/views/index.blade.php

...
  {!! $title !!}
  @while(have_posts()) @php(the_post())
    @includeFirst(['partials.content-' . get_post_type(), 'partials.content'])
  @endwhile
...

resources/views/partials/content.blade.php

... 
  <header>
    <h2 class="entry-title">
        {!! $title !!}
    </h2>
  </header>
...

app/View/Composers/Index.php

...
public function title() {
  return get_the_title();
}
...

app/View/Composers/Content.php

...
public function title() {
  return get_the_title();
}
...

This is an extremely rudimentary example, and there are better ways of doing the title specifically, but this would get the correct title in each case, so it acts like a Sage 9 static controller function.

2 Likes

Trying! Thank you very much Michael.

I haven’t tested this inside the loop, but you can return anonymous functions as variables and then execute them in your blades. Since iirc the loop relies on global state they should work. i.e.:

// SomeComposer.php
public function with()
{
  return [
    'cat_links' => function() {
      $cats = get_the_category();
      $output = "";
      foreach ($cats as $cat) {
          $output .= get_category_link($cat->slug);
      }
      return $output;
    },
  ];
}
// some-view.blade.php
{{ $cat_links() }}
4 Likes

Ok, Thanks. I will try it too.

This topic was automatically closed after 42 days. New replies are no longer allowed.