How to use variables from another layout?

  • Hi,

    I get how to pass a variable into a layout, like this:

    1. // template.php
    2. perch_layout('head', array(
    3. $demo => 'THIS IS A DEMO',
    4. ));

    Then inside head.php I'd use this:

    1. // head.php
    2. perch_layout_var($demo);

    which would output THIS IS A DEMO. Great.

    Is it possible to do the reverse? Pull a variable out of perch_layout('head')?

    At the top of post.php I have perch_layout('head'), this contains lots of global php variables I'd like reuse in other templates.

    As an example, in perch_layout('head') I have this variable:

    1. // head.php
    2. $test = 'THIS IS A TEST';

    I'd like to use $test in post.php

    1. // post.php
    2. perch_layout('head');
    3. // Using pipit add-on to format print_r
    4. pipit_r($test);

    In perch debug I get an error: [message] => Undefined variable: test

    Is there a way to use $test in a template without having to recreate it?

  • Hi Stephen,

    You can use PerchSystem::set_var() and PerchSystem::get_var():

    1. // inside layout
    2. PerchSystem::set_var('my_variable', 'some value');

    1. perch_layout('head');
    2. $my_variable = PerchSystem::get_var('my_variable');

    Note that set_var() makes the variable available for the template engine. You can always unset it if you no longer need it:

    1. PerchSystem::unset_var('my_variable');