I’ve been struggling to get to grips with Sage 10 this week, having only minimal PHP knowledge beforehand which I assume is part of what’s tripping me up.
I’m stumped on how I get a partial (for example, a button) to be used in multiple parts of my page and still be able to define the data for each individual instance. Here is my problem:
<?php
namespace App\View\Composers;
use Roots\Acorn\View\Composer;
class Page_home extends Composer
{
protected static $views = ['page_home'];
public function with()
{
return [
'page_header_heading' => 'My heading',
'page_header_subtext' => "Text here",
'button_content' => 'Get In Touch',
'button_href' => 'mailto:email@email.com',
'button_id' => 'headButtonCta',
];
}
}
Now let’s say I wanted to add a second instance of the button partial either in the page header or even elsewhere on the main page template. They will all get the same values as eachother. How do I give them all unique values?
Look into components, for reusable elements that you need to pass parameters. You can use something like: wp acorn make:component CtaButton , then you’ll have a component class much like a composer, but you just need to add your parameters to the constructor, i.e.
/// app/View/Components/CtaButton.php
<?php
namespace App\View\Components;
use Roots\Acorn\View\Component;
class CtaButton extends Component
{
public $buttonContent;
public $buttonHref;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($buttonContent, $buttonHref = null)
{
$this->buttonContent = $buttonContent;
$this->buttonHref = $buttonHref;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return $this->view('components.cta-button');
}
}
Then on the tamplate for the component, something like:
// components/cta-button.blade.php
Note that the attribute names will become camelCase within the class. To pass a variable to the attribute prepend : as in :button-href.
Worth looking into the blade docs on how to use slots in components as well.
This should output 10 instances of my partial, which it does. In order to give the correct values to the correct partials in my view composer, I’d need to assign a key to each (like $card1). The problem is, i don’t know how to increment the number at the end in a way that works. I’ve tried