Jump to content

Matrix repeater - can you change which file is used by $item->render()?


sodesign
 Share

Recommended Posts

Hi everyone,

I'm using a Matrix Repeater field called 'items', and looping through like this:

foreach($page->items as $item) {
	echo $item->render();
}

This automatically uses the fields/items/[item-type].php file to render the field.
Is there a way to programatically change either the filename or the directory this uses?

Thanks!
Tom

Link to comment
Share on other sites

Yes of course. We're working on a big redesign of an existing site with around 40 templates and almost 100 fields. We're updating one section at a time, and currently we're selecting the templates, partials etc based on the page and the user's role by passing a different path into wireRenderFile.

We haven't found a way to dynamically change the field templates used. 

Link to comment
Share on other sites

Looking at the RepeaterMatrixPage render() method for v0.0.8, you can pass in a file path that will be used for rendering.

In the DocBlock for that method it says: "* @param string $file Optional render file, if providing a field name too". But looking at the code, it actually does not require to pass a field name in order to pick up the $file param.

So inside your foreach you can implement some logic based on user role and page to pass in a custom render file

/** @var RepeaterMatrixPage $item */
foreach($page->items as $item) {
    $renderFile = ($item->getForPageRoot()->foo == 'bar' && $user->hasRole('baz')) ? '/path/to/custom/renderfile.php' : '';
	echo $item->render('', $renderFile);
}

 

  • Like 2
Link to comment
Share on other sites

I once added a field to my repeater-fields to switch files.

It was called something like "theme" or "style" and when something was selected in it, I just took the value, pointed it to the "new" layout/render file and went from there. So... in some kind an alternate render file, yet controllable.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...