Collection data as variable into perch layout

  • I'm trying to set the value of 'department' in a collection called 'Jobs', I want to use this variable inside a perch_layout to set as class on the body tag:

    Code
    1. if (perch_get('s')) {
    2. $department = perch_collection('Jobs',[
    3. 'template' => 'jobs/jobs_listing_department.html',
    4. 'filter' => 'job_slug',
    5. 'match' => 'eq',
    6. 'value' => perch_get('s'),
    7. 'count' => 1,
    8. ]);
    9. }

    The above outputs the department name as expected but displays on the page, I wanted to set/use it as a variable inside the below code:

    Code
    1. perch_layout('global.header', [
    2. 'title' => perch_page_title(true),
    3. 'page' => $department,
    4. // loads extra custom header default | ppc | no-module
    5. 'header-extra' => 'extra.header.job',
    6. ]);

    Then 'page' is used to add the department name as a class on the body tag.

    PHP
    1. <body class="<?php perch_layout_var('page'); ?>">

    The field used when adding a job to the Jobs collection template is:

    Code
    1. <perch:content id="department" type="select" label="Department" options="Accounts|accounts,Marketing|marketing,Sales|sales"/>

    Please does anyone have any ideas on how to do this?

  • Gareth S

    Approved the thread.
  • One option is to add this to your function:

    PHP
    1. 'skip-template' => true,'return-html' => true,

    to stop it displaying on page.


    Then right after the function, do this....

    Code
    1. if(isset($department[0])) {
    2.     $dept_name = $department[0]['department'];
    3. }


    Then you can use $dept_name in your layout


    Code
    1. perch_layout('global.header', array(
    2.     'bodyclass' => $dept_name,
    3. ));


    Minor thing, but I used "bodyclass" instead of "page" to avoid confusing with generic names.

  • That worked perfectly, thank you!


    Have updated page to bodyclass too, thanks. Here's the full code for others: