Roots Discourse

Question regarding View Composers and $views

In the explanation for using these on Roots.io, the examples are using $views to build an array of the views associated with it. My question is, why do these have to implicitly be declared? Maybe I’m misunderstanding things but why not just build all composers to be able to be accessed in views as needed (without having to update the composer)? Methods with images, products (I’m using Woo), etc. will potentially be used in multiple places so this is confusing me. Thanks…

Having specific Composers correspond to specific blades is a huge part of the benefit of them: It allows you to effectively scope variables to a specific partial, so you don’t have to worry about naming collisions for your variables (well, as much).

If you’re going to be using the same stuff in more than one place, then make a partial that can be used in all those places and then make a Composer for that partial (or just make a Component).

The newer versions of Sage 10 also support automatically matching Composers to views without explicitly declaring them. i.e. you can do this:

// resources/partials/cards/post.blade.php
<div>{{ $title }}</div>

// app/Views/Composers/Partials/Cards/Post.php
namespace App\View\Composers\Partials\Cards;

class Post extends \Roots\Acorn\View\Composer {
  public function with() {
    return [
      'title' => get_title_for_this_card(),
    ];
  }
}

If you really really want your composer to be available to every view, you can just give it a wildcard:

namespace App\View\Composers;

class Something extends \Roots\Acorn\View\Composer {
  public static $views = [ '*' ];
  public function with() {
    return [
      'i_am_available_in_every_view' => get_this_variable(),
    ];
  }
}

Ahh, I get it now. Thank you very much for the reply and examples.

1 Like

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