Jump to content

Accessing values from “parent” template when page is rendered within another template


Oliver
 Share

Recommended Posts

When I for example generate a list of articles, I get my pageArray through the API within another page’s template, iterate through it and call the render method for output. Works great. But what to do if I wanted to make the template of these articles behave in a certain manner depending on the the context (the current page’s template) the render method is called from? Is there a way to access the vars existing within the current page’s template or even the current page’s field values on rendering from the articles’ template? To check “Am I rendered within/from another page’s template?” and “Is the var $xy or the field ‘ab’ set to ‘brabra’ in the other page I’m rendered in/from?”

Link to comment
Share on other sites

You could use the template class to render the template and set vars being "sent" to it. Not sure if that's what you're looking for.

$t = new TemplateFile($config->paths->templates . "{$some_template_name}.inc");
$t->set( "mypage", $page );
$t->set( "articles", $some_articles );
echo $t->render();
Link to comment
Share on other sites

When you do something like this:

$p = $pages->get('/some/other/page/');
echo $p->render();

…the $page API var is set to $p for the duration of the render() method. Meaning the original context ($page) is not visible to the system, only /some/other/page/. Once render() finishes, PW sets $page back to the original, if there was one before it. Perhaps we need to maintain an accessible stack of them for the API. But the way you could do it now would be to create an autoload hook, and save the value of $page from a ready() function, i.e.

class Test extends WireData implements Module {
public static function getModuleInfo(return array('title' => 'test', 'version' => 100, 'autoload' => true));
public function init() { /* needs to be here, but not used */ }
public function ready() { $this->setFuel('originalPage', $this->page); }
}

In the above, you'd be setting a new API variable called $originalPage that would always have the originally loaded page so that you could refer to it when needed.

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

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

×
×
  • Create New...