# ACF variables in blade template

**URL:** https://discourse.roots.io/t/acf-variables-in-blade-template/10180
**Category:** sage
**Tags:** sage9, blade
**Created:** 2017-08-09T16:33:48Z
**Posts:** 61

## Post 1 by @mellis84 — 2017-08-09T16:33:49Z

Hey Guys!

What’s the best place to keep my Advanced Custom Fields variables?  
I know it’s bad practice to have anything like this in a blade template… so where could I store them and call them into the template?

Cheers!

```
<?php
    // variables
    $subheading = get_field('subheading');
    $video = get_field('video_link');
    $buttons = have_rows('buttons');
    $backgroundOverlay = get_field('background_image_overlay');
?>

<section class="introduction <?php if( $backgroundOverlay ): ?>introduction--with-overlay<?php endif; ?>" 
         style="background-image: url('<?php the_post_thumbnail_url(); ?>')">
    <div class="introduction__content">
        <div class="container container--fixed-lrg">
            <h1>{!! App\title() !!}</h1>
            <?php
                if( $subheading ):
            ?>
                <h2><?= $subheading ?></h2>
            <?php
                endif;
                if( $buttons ): 
            ?>

                <div class="btn-group">
                    <?php 
                        while( have_rows('buttons') ): the_row(); 

                        $text = get_sub_field('text');
                        $colour = get_sub_field('colour');
                        $link = get_sub_field('link');

                    ?>
                        <a href="<?= $link ?>" class="btn btn--lrg <?= $colour ?>">
                            <span><?= $text ?></span>
                        </a>
                    <?php 
                        endwhile; 
                    ?>
                </div>

            <?php 
                endif; 
                if( $video ):
            ?>
                <div class="video-container">
                    <div class="embed-container">
                        <iframe class="videoIframe js-videoIframe" 
                                src="" 
                                frameborder="0" 
                                allowTransparency="true" 
                                allowfullscreen 
                                data-src="{!! App\videoThumbnail($src) !!}">
                        </iframe>
                        <button id="playButton" class="videoPoster js-videoPoster" 
                                style="background-image:url({!! App\videoThumbnail($src)[1] !!}">
                                Play video
                        </button>
                    </div>
                </div>
            <?php
                endif;
            ?>
        </div>
    </div>
</section>
```

---

## Post 2 by @smutek — 2017-08-09T17:09:31Z

Create a controller for them.

Have a look here for an explanation & setup: [GitHub - soberwp/controller: Composer package to enable a controller when using Blade with Sage 9](https://github.com/soberwp/controller)

You might browse this thread as well, if you haven’t already.  
[https://discourse.roots.io/t/best-practice-resources-for-blade/8341/11?u=smutek](https://discourse.roots.io/t/best-practice-resources-for-blade/8341/11)

I linked to the post where I got all giddy when it hit me how awesome this setup is.

Hopefully this helps some, I haven’t been on the board lately and others may be able to provide some better examples.

---

## Post 3 by @mellis84 — 2017-08-09T21:42:14Z

Awesome, I was wondering if I should put them in the helpers.php or a controller, those links really help explain how it works. Thanks heaps @smutek :slight_smile:

---

## Post 4 by @mellis84 — 2017-08-10T12:47:42Z

Sorry I just have one more question!

So say i make a controller for my homepage template:

```
public function images()
    {
        return get_field('images');
    }
```

and Just display it in my template eg:

```
{{$image['alt']}}
```

Rather than creating a bunch of functions to return one field, I should be able to create one function in the controller that uses all the fields i have in my first comment like:

```
public function homepageFields()
    {
        return array (
         $subheading => get_field('subheading'),
         $video = get_field('video_link')
       )
    }
```

Would that be the right syntax / way of going about it? and how would I display, the $video in the array, in the template? if it’s in the App namespace, ie:

```
{!! App\homepageFields($subheading) !!}
```

??

Cheers :slight_smile:

---

## Post 5 by @alwaysblank — 2017-08-10T14:28:02Z

In your second example, you’d be able to access `video` in your Blade with the following:

```
{{$homepage_fields['video']}}
```

Methods in the App namespace are available to _every_ Blade, unless they’re overwritten by another controller–i.e. if you had a `controllers/FrontPage.php` controller file that also defined `homepageFields()`, the `$homepage_fields` variable in `views/front-page.blade.php` would contain the value returned by the `controllers/FrontPage.php` version of `homepageFields()` instead of the one defined in `controllers/App.php`.

Personally, I don’t like to group unrelated data together in the variables I pass from my controllers to my Blades, because then my templates become more opinionated about how they handle data. That being the case, I’d separate out `subheading` and `video` instead of returning them as an array, but that’s a personal preference.

---

## Post 6 by @nathobson — 2017-08-10T14:34:30Z

I’m currently working like this:

**Controller (`controllers/Home.php`)**

```
public function location()
{
    return (object) array(
        'title' => get_field('location_title'),
        'button_text' => get_field('location_button_text'),
        'button_link' => get_field('location_button_link')['url'],
    );
}
```

**View (simplified)**

```
<h2>{{ $location->title }}</h2>
<a href="{{ $location->button_link }}">{{ $location->button_text }}</a>
```

I like object syntax personally.

I split my templates down into components (`location` is a component used on the home page) and then use a method per component. I feel like this keeps everything nice and logical.

---

## Post 7 by @mellis84 — 2017-08-10T14:54:38Z

@alwaysblank @nathobson Thanks so much for your suggestions, I should probably get more of an understanding with MVC and take some courses :stuck_out_tongue: .

Really appreciate the help guys!

---

## Post 8 by @nathobson — 2017-08-10T15:18:34Z

No problem. All pretty new to me too but once you’re past the initial learning curve, it all clicks very nicely. Having super clean views/templates is particularly satisfying. Maintainability is also greatly improved thanks to the separation of logic and templating. I find that once all the logic is taken care of, moving stuff around/amending your templates is really easy.

---

## Post 9 by @mellis84 — 2017-08-10T15:25:42Z

It is awesome, that’s what I love about React.js, it’s funny, where I work, we run an MVC environment but it’s such a mess, with php logic and everything in-between mashed into the templates haha so it’s good to understand the proper way of doing it :slight_smile:

---

## Post 10 by @MWDelaney — 2017-08-10T15:32:53Z

> [@nathobson](#):
>
> the separation of logic and templating

This is what I like the most. I can shove all the ugly logic I need into a controller and keep my template clean with `{{ $resultOfUglyLogicOhGodDontLookAtIt }}`

---

## Post 11 by @nathobson — 2017-08-10T15:55:52Z

Only thing is my directory structure is getting pretty crazy. More and more structure = more and more directories :smile:

Flipping between assets, controllers, views and whatever partials inside sub-directories of all of those.

---

## Post 12 by @alwaysblank — 2017-08-10T16:10:18Z

Using object syntax like this is very clever and I like it a lot! I realize it’s mostly aesthetic preference on my part, but for some reason `$container->field` always looks so much nicer to me than `$container['field']`.

---

## Post 13 by @olafghanizadeh — 2017-08-11T04:27:07Z

I’m just getting started here, but this has really given me new hope for Wordpress. I always got frustrated that my template files would get so messy when you started adding logic for ACF fields and so on.

I have created this Related Posts snippet. It utilizes an ACF Bidirectional Post Relationship plugin. The code is as follows:

```
<?php global $post; ?>
<?php $related_posts = get_field( 'related_posts' ); ?>
<?php if ( $related_posts ): ?>
	<?php foreach ( $related_posts as $p ): ?>
    {{the_post_thumbnail( 'thumbnail', array( 'class' => 'card-img-top img-fluid' ) )}}
	{{get_permalink( $p )}} 
    {{get_the_title( $p )}}
    
	<?php endforeach; ?>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>
```

Ideally I’d like to remove as much as the logic from the template file. I’ve seen the examples above and I think I get it, but the `global $post`, The loop and `wp_reset_postdata` confuses me.

---

## Post 14 by @nathobson — 2017-08-11T08:35:44Z

I can’t say this is the most elegant way of doing it but perhaps something like:

**Controller**

```
public function related()
{
    global $post;

    $data = [];

    $related_posts = get_field('related_posts');

    foreach ($related_posts as $p) {

        $this_post = (object) array(
            'thumbnail' => get_the_post_thumbnail($p, 'thumbnail', array('class' => 'card-img-top img-fluid')),
            'permalink' => get_the_permalink($p),
            'title' => get_the_title($p),
        );

        array_push($data, $this_post);
    }

    return $data;
}
```

**View**

```
@foreach ($related as $p)

    {{ $p->thumbnail }}
    {{ $p->permalink }}
    {{ $p->title }}

@endforeach
```

Totally untested and assumes that your returning your related post as the post ID not an object (by looking at what you posted up). It involves two loops (one in the controller and one in the view) but it keeps the view very tidy in my opinion.

---

## Post 15 by @nathobson — 2017-08-11T08:38:30Z

> [@alwaysblank](#):
>
> Using object syntax like this is very clever and I like it a lot! I realize it’s mostly aesthetic preference on my part, but for some reason $container-\>field always looks so much nicer to me than $container[‘field’].

This 100% for me :slight_smile:

---

## Post 16 by @Log1x — 2017-08-11T10:17:34Z

Been using ACF Fluent (with controller of course) and have been very pleased.

> **[samrap/acf-fluent](https://github.com/samrap/acf-fluent)**
>
> acf-fluent - A fluent interface for the Advanced Custom Fields WordPress plugin

Also semi related and worth checking out is:

> **[StoutLogic/acf-builder](https://github.com/StoutLogic/acf-builder)**
>
> acf-builder - An Advanced Custom Field Configuration Builder

I use both in every project I work on now. They are wonderful and really bring ACF to the next level for me.

---

## Post 17 by @olafghanizadeh — 2017-08-11T11:25:16Z

Thank you. It works. However, I don’t see what the $data variable is doing?

---

## Post 18 by @nathobson — 2017-08-11T12:08:09Z

Each field within the post gets stored in the `$this_post` object within the `foreach` loop which is then added as a new property within the `$data` object.

---

## Post 19 by @withjacoby — 2017-08-23T15:07:45Z

It would be fairly easy to build in an acf helper class into Controller that speeds up the process of looping through fields and then outputting to an object notation. All you would need to use in the view then would be `@foreach` (for repeater fields). Basic fields could be flattened using the key as the variable name.

If you’re using acf in a standard way, it could all be automated to be honest. I’m going to look into building a prototype module over the next few days should time allow.

---

## Post 20 by @withjacoby — 2017-09-01T20:16:17Z

Been working on something like this. All values returned to the view are returned in object notation should that be required.

**In a Controller Class;**

```
<?php

namespace App\Controllers;

use Sober\Controller\Controller;
use Sober\Controller\Module\Acf;

class Single extends Controller
{
    // all returned values from Acf, even if multidimensional arrays are in object notation 

    public function acf()
    {
        return Acf::get();
        // gets all fields
        // use $acf->repeater in view
        // use $acf->text_field in view
    }

    public function text()
    {
        return Acf::get('text_field');
        // gets 1 field and returns flattened
        // use $text in view
    }

    public function combo()
    {
        return Acf::get(['repeater_field', 'text_field']);
        // gets 2 fields, and returns in object notation using advanced custom fields key values
        // use $combo->text_field in view
        // use $combo->repeater_field in view
    }
}
```

---

## Post 21 by @withjacoby — 2017-09-02T09:34:41Z

Just did more work on automating the acf fields from Controller to view.

The returned variables are based on acfs key values. You can then override any values by using the same key value in camel case in your Controller for more control.

```
<?php

namespace App\Controllers;

use Sober\Controller\Controller;

class Single extends Controller
{
    protected $acf = true;

    public function textField()
    {
        return 'Override automated field';
    }
}
```

**@debug**

```
$site_name » string
$post » object
$text_field » string
$repeater_field » array[2]
```

Multilevel dimensional arrays are returned in object notation based on your acf field keys.

Repeater field example below;

```
<h1>Repeater Field</h1>
<ul>
  @foreach($repeater_field as $item)
    <li>{{ $item->repeater_field_item }}</li>
  @endforeach
</ul>
```

---

## Post 22 by @threehz — 2017-10-03T21:43:05Z

Hey all,

I’m trying to get ACF fields working and an encountering some issues.

I’m running the most recent Sage beta, and I can not figure out how to get the fields exposed as simple variables as I see everyone doing here.

Note that my image field is just returning the URL string.

Controller `app/controllers/App.php`:

```
namespace App;

use Sober\Controller\Controller;

class App extends Controller
{
    public function heroImg()
    {
        $image = get_field('hero_image');
        return $image;
    }
}
```

working `views/partials/content-page.blade.php`

```
@if (App::heroImg())
  <div class="bg-img" style="background-image: url('{!! App::heroImg() !!}')">
@endif
```

not working:

```
@if ($heroImg)
  <div class="bg-img" style="background-image: url('{{ $heroImg }}')">
@endif
```

I feel like the latter should be working based on what I see in this thread. Did I miss a step? Thank you!

---

## Post 23 by @threehz — 2017-10-03T22:12:39Z

I just figured this out, I missed an important bit in [https://github.com/soberwp/controller/blob/master/README.md](https://github.com/soberwp/controller/blob/master/README.md)

**Important: The method name is converted to snake case and becomes the variable name in the Blade view.**

`heroImg()` becomes `$hero_img` and now all works fine.

Hope this helps anyone else with the same issue!

---

## Post 24 by @nboliver — 2017-10-06T22:07:34Z

This looks nice! Would you mind sharing the Acf class too?

---

## Post 25 by @Webstractions — 2017-10-11T22:57:09Z

@threehz Been there, done that. It is one of the most confusing things about `Controller`.

I wished there was a simpler way of defining data without going through a separate function for each variable.

---

## Post 26 by @nathobson — 2017-10-12T07:03:32Z

Did you read the whole thread? You absolutely don’t need a separate function for each variable. Just build an array/object of your data to return within your method.

---

## Post 27 by @jdarrohn — 2017-10-12T13:37:47Z

This is clever. I feel like this is how I will do it moving forward.

---

## Post 28 by @Webstractions — 2017-10-12T14:06:50Z

@nathobson

> Did you read the whole thread? You absolutely don’t need a separate function for each variable. Just build an array/object of your data to return within your method.

Yes. My comment “been there, done that” was about snake casing of the method names BTW.

Whether you package all the variables into an array, object, or even a collection, wasn’t my point. On the Blade side, you have to do `$object->related` and `$object->unrelated` kind of thing or define separate functions for the unrelated.

Either way, when does it stop being a `controller` and actually be a `transformer`, or both. Just confusing, is all I am saying.

---

## Post 29 by @shaimoom — 2017-12-18T18:18:55Z

Similar to @olafghanizadeh’s post, I am trying to display the ACF Post Object on `front-page.blade.php`. I first tried to display using vanilla php (using [ACF’s Post Object article](https://www.advancedcustomfields.com/resources/post-object/)) before attempting to use proper blade and controller syntax just to see if it works:

```
@extends('layouts.app')

@section('content')

  <?php $post_object = get_field('featured_article'); ?>
  <?php if($post_object): ?>
    <?php $post = $post_object; ?>
    <?php setup_postdata($post); ?>
    <div>
      <h3><a href="{{ the_permalink() }}">{{ the_title() }}</a></h3>
    </div>
  <?php wp_reset_postdata(); ?>
  <?php endif; ?>

@endsection
```

However, it is displaying the link and title of the Home page and not the selected Post in ACF editor:

 ![ACF-post-object](https://discourse.roots.io/uploads/default/original/2X/3/3dfd08dc55a98cd4e5d8275d025d79646dc71b9d.png)

I also, viewed the data using `print_r` and it is properly grabbing the selected Post data. Thanks in advance for anyone’s help!

---

## Post 30 by @MWDelaney — 2017-12-18T18:29:54Z

Try the “Basic loop (without setup\_postdata)” method from [the ACF relationship documentation](https://www.advancedcustomfields.com/resources/relationship/).

---

## Post 31 by @shaimoom — 2017-12-18T18:45:02Z

The basic loop method is also displaying the link and title of the Home page. Here is the code I used from the documentation:

```
@extends('layouts.app')

@section('content')

<?php $posts = get_field('featured_article'); ?>
<?php if( $posts ): ?>
  <ul>
  <?php foreach( $posts as $p ): ?>
      <li>
        <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>
      </li>
  <?php endforeach; ?>
  </ul>
<?php endif; ?>

@endsection
```

---

## Post 32 by @MWDelaney — 2017-12-18T21:40:16Z

I’m doing exactly what you’re doing in several themes (I just double-checked my code) and it’s working. Are you sure your field is named `featured_article` ?

If you add `print_r($p)` right after your `foreach` does it give you info about the featured article?

---

## Post 33 by @shaimoom — 2017-12-18T22:23:15Z

I got it to work with the last code block I posted using the Relationship ACF Field Type and your tip to use the Basic loop method. However, the Post Object keeps displaying the Home page. That’s ok though, I can use the Relationship Field Type for the purpose of this page and I got it to work with controller/blade syntax as well. Thanks so much for the help!

---

## Post 34 by @withjacoby — 2017-12-30T08:58:21Z

I’ll be sharing the Acf module for Controller with the next release which should be soon.

The automation will speed up a lot of this repetitive work for each field.

---

## Post 35 by @marcialsoto — 2018-04-19T18:34:14Z

The documentation says: "Controller has an useful Advanced Custom Fields helper module to automate passing on fields.

The automated fields will use the variable names from Advanced Custom Fields and pass them onto the view."

How, can i call it from the view (i am using in my category archive)?

I cant see nothing when i use the @debug

---

## Post 36 by @withjacoby — 2018-04-20T09:10:54Z

I would recommend raising an issue on the GitHub repo and I’ll take a look for you.

---

## Post 37 by @jakus — 2018-05-17T06:07:33Z

Hi there, do you know when Controller 2.0.0 is going to be used by Sage as a default?

Are there any potential issues with updating this manually in order to get the most out of the ACF module you’ve so brilliantly created? As suggested in this thread: [Setting up a controller for ACF fields](https://discourse.roots.io/t/setting-up-a-controller-for-acf-fields/11759/21)

How will this be affected by future updates to Sage?

Cheers,  
J

---

## Post 38 by @withjacoby — 2018-05-17T14:18:24Z

You can just bump the version in package.json. Here’s the files that need to change with the upgrade to 2.0.x

> <https://github.com/roots/sage/pull/2025>

---

## Post 39 by @brandonvhuynh — 2018-05-21T06:47:21Z

I see lot of comments about using/accessing variables with get\_field.

How about get\_sub\_field inside of a flexible field group?

---

## Post 40 by @nathobson — 2018-05-21T07:49:31Z

Easy way would be to use `get_field` and store the flexible field data into a variable and then `foreach` over it to access the data you need (in your controller).

---

## Post 41 by @SRawhloe — 2018-05-21T16:36:13Z

Is there a way to include partials in the controller while using flexible content field, not just single field data?

What I’m trying to do is to have the usual acf check for the flexible content field in the controller, get the corresponding partial and then display the whole thing in the view file, while each partial can show its own sub fields.

Basically I’m trying to make a simple page layout builder in the back-end and I use the flexible content field for that. There would be these pre-made page sections like a page-banner, or a basic text content with title or a gallery, etc. And I want to make all these as individual partials. Just can’t really figure out how to make the controller spit it out on the page.

Not sure if I tackled the problem from the right direction, I just started learning the new sage and blade templating in general a few hours ago. I tried to avoid doing it with my old way which is having the acf if/while checks then including the specific partial in the page template file.

Any examples and help are greatly appreciated.

---

## Post 42 by @brandonvhuynh — 2018-05-24T06:51:29Z

I am also doing the same thing. I have gotten to the point where I can display different content per ACF shelf but it does not utilize the controller.

i did have a solution where i could use multiple ACF controllers on any page; however, when i wanted to reuse a flexible content shelf on the same page, it would return the value of the first content row.

Example:  
Home Page : Flexible Content : Row 1 - Content, Row 2 - Image, Row 3 - Content. The values of the variables from the content controller - Row 1 and Row 3 - are the same on the front end, but on the back end they are different.

---

## Post 43 by @SRawhloe — 2018-05-24T09:11:56Z

I ended up putting together something based on nathobson’s tips in the controller, but let the partial handling in the view file. That wasn’t my original goal but I thought that much logic is okay(or necessary) since it is the same how it is in the default pre-made files.

controller:

```
public function getLayouts()
  	{

      $layouts = get_field('layout');
      $data = [];
      if($layouts):
        foreach($layouts as $layout):

          // common layout attribute settings
          $this_layout = (object)[
            'background_color' => $layout['settings']['background_color'],
            'background_image' => $layout['settings']['background_image'],
            'custom_class' => $layout['settings']['custom_class']
          ];
          // specific attributes based on layout type
          if($layout['acf_fc_layout'] == 'large_carousel'):
            $this_layout->type = 'large_carousel';
            $this_layout->slides = $layout['carousel_slides'];
          elseif($layout['acf_fc_layout'] == 'text_section'):
            $this_layout->type = 'text_section';
            $this_layout->full_width = $layout['settings']['full_width'];
          endif;

          array_push($data, $this_layout);

        endforeach;
        return $data;
      endif;
  	}
```

View:

```
@foreach($get_layouts as $layout)
      @if($layout -> type == 'large_carousel')
        @include('partials.page-section-carousel')
      @elseif ($layout -> type == 'text_section')
        @include('partials.page-section-text')
      @endif
    @endforeach
```

Inside a partial a you can get the values you set up for the object with $layout -\> somestuffyouneed.

It isn’t much more efficient than the regular acf while loop but at least the flexible content data is available in the controller now. Not sure if it helps in your case but maybe you can get some ideas and improve my mess.

edit: Oh and I used this for debug purposes in the loop to check how ACF made the structure:

```
echo '<pre>';
  print_r($layout);
  echo '</pre>';
	      die;
```

---

## Post 44 by @brandonvhuynh — 2018-05-27T20:43:26Z

How are you reusing the same template on the same page?

---

## Post 45 by @SRawhloe — 2018-05-27T21:07:41Z

it’s there in the code examples really. In the controller I build an array of layout objects from the acf input and in the view it goes through the array and displays the corresponding layout template. It doesn’t matter how many times you put in the same template in the back end because they become different objects in the controller.

There are some stuff there that is specific to my case but the main part is the $this\_layout which is current object that will be put into the $data array.

---

## Post 46 by @SRawhloe — 2018-05-27T21:21:37Z

maybe this way it’s clearer:

controller:

```
public function getLayouts()
{
	//acf flexible content field
	$layouts = get_field('layout');
	//this will hold all the layouts
	$data = [];
	//go through each layouts that got put in there
	if($layouts):
		foreach($layouts as $layout):

			//$this_layout is the current one
			$this_layout = (object)[
				//the layout object's title value will be the 'title' named acf sub field of the flexible content layout
				$this_layout->title = $layout['title'];
			];

			// if you want to add specific fields based on flexible content layout type, you can check it this way
			if($layout['acf_fc_layout'] == 'text_section'):
				//the layout object's type value is going to be 'text section'
				$this_layout->type = 'text_section';
			endif;

			//put the current object into the $data array
			array_push($data, $this_layout);

		endforeach;
		//return the $data array with all the flexible content objects in it
		return $data;
	endif;
}
```

view file

```
@extends('layouts.custom')

@section('content')
  @while(have_posts()) @php the_post() @endphp

		//get_layouts function from the controller and run through each
    @foreach($get_layouts as $layout)
			//if the object's type value is 'text_section' then do this
      @if ($layout -> type == 'text_section')

        <section class="page-section standard-text-section">
					<div class="container">
						<div class="text-wrapper">
              //display one of the sub field values we set up in the controller this way
							<h1>{{$layout -> title}}</h1>
              <p>{{$layout -> type}}</p>
						</div>
					</div>
				</section>

      @endif
    @endforeach

  @endwhile
@endsection
```

---

## Post 47 by @jakus — 2018-06-07T07:00:35Z

Hi Jacoby, love your work here. Thanks for all your help.

Just wondering how this ACF module works using `get_option('page_for_posts')`

As an example I’m trying to get a custom field on a blog page, but when I @debug using protected `$acf = ['field1'];` returns no data.

---

## Post 48 by @withjacoby — 2018-06-07T07:15:19Z

The new version releasing soon will have support for acf option page. You would just just use $acf = true; in App.php

---

## Post 49 by @jakus — 2018-06-07T07:16:39Z

Appreciate it mate… Don’t mean to pester but any idea when the new version may released?

In the meantime should I just forgo using the ACF module and use the original method?

---

## Post 50 by @withjacoby — 2018-06-10T12:17:58Z

I’ll tag it this afternoon.

---

## Post 51 by @joshb — 2019-03-30T00:57:10Z

First of all, thanks for this post as we’re able to use this to have clean templates!

If one were trying to return the default WP thumbnail cropped image size from an ACF image field in a repeater field, what’s the best way to do that? Also, how to correctly grab the alt tag for the image?

Controller:

```
public function models()
{
    return array_map(function($model) {
        return [
            'title' => $model['model_type_name'] ?? null,
            'content' => $model['short_description'] ?? null,
            'image' => $model['image'],
            'aluminum' => $model['aluminum_colors'] ?? null,
            'poly' => $model['poly_roof_colors'] ?? null,
            'heat' => $model['heat_poly_roof_colors'] ?? null,
            'wind' => $model['wind_pressure'] ?? null,
            'snow' => $model['snow_load'] ?? null,
        ];
    }, get_field('model_series') ?? []);
}
```

Loop:

```
@foreach($models as $model)

<div @include('partials.content-single-our_models_list', $model) </div>

@endforeach

</div>
```

File:

```
<h3>{ $title }}</h3>

<img src="{{ $image }}" alt="{{ $image ['alt'] }}">
```

Lastly, how would you go about returning the values of a set of checkboxes if they’re checked?

```
@if($aluminum['slc'])
    @php echo "sun silver"; @endphp
@else
    @php echo "n/a"; @endphp
@endif
```

---

## Post 52 by @djmtype — 2019-05-25T18:35:08Z

[shaimoom](https://discourse.roots.io/u/shaimoom) I was running into the same exact issue. Instead of `{{ the_permalink() }}` and `{{ the_title() }}`, try `{!! the_permalink($post) !!}` and `{!! get_the_title($post) !!}` so long as you’re using the blade syntax.

Otherwise, follow this pattern for vanilla php: `<?php echo get_the_title($post); ?>`.

These both worked for me.

I’m new to blade and come from Sage 8, so there’s probably a cleaner way to handle this setting up a controller. If you know how, please let me know.

---

## Post 53 by @SergiArias — 2020-05-08T19:06:36Z

I have one question. Let’s say we want to create a variable based on acf fields to show in the blade files. Just to keep the logic out of the blade template.  
I would still have to use the get\_field within the methods, or is there a way to access the acf variables created with $acf = true within the controller?

Out of simplicity, In your example imagine that instead of overriding the text\_field variable, you want to take the acf variable and append some text to it. How would you do it?

Thanks!

---

## Post 54 by @joshb — 2020-05-14T20:34:28Z

I have a custom post type: Portfolios.  
This post type has a handful of ACF fields in a group:

```
<?php

namespace App\Controllers;

use Sober\Controller\Controller;

class SinglePortfolio extends Controller
{
    public function portfolio()
    {
        $field = get_field('portfolio');
        return (object) [
            'slider' => $field['slider'] ?? null,
            'name' => $field['name'] ?? null,
            'location' => $field['location'] ?? null,
            'description' => $field['description'] ?? null,
            'awards' => $field['awards'] ?? null,
            'photos' => $field['photos'] ?? null,
        ];
    }
}
```

The home page has an ACF relationship field to allow me to choose 3 portfolio items to displayed in a loop on the home page:

```
<?php

namespace App\Controllers;

use Sober\Controller\Controller;

class FrontPage extends Controller
{

    public function featured() {
    global $post;
    $data = [];
    $featured = get_field('featured_portfolios');
        foreach ($featured as $f) {
            $this_post = (object) array(
                'thumbnail' => get_the_post_thumbnail($f, 'hero', array('class' => 'lozad')),
                'permalink' => get_the_permalink($f),
                'title' => get_the_title($f),
            );
            array_push($data, $this_post);
        }
        return $data;
    }
}
```

The regular post data from WP (thumb, permalink, title) all pull that data to the home page loop just fine:

```
@foreach ($featured as $f)
    <div class="relative w-full md:w-1/2">
        <div class="p-4">
            <a href="{{ $f->permalink }}" title="{{ $f->title }}">       
                <div class="absolute top-0 right-0 bottom-0 left-1/2 bg-secondary opacity-20 z-50 m-4 p-4">
                    <div class="absolute bottom-0 right-0 text-right text-white pr-8 pb-8">
                        <p class="m-0">{{ $f->title }}</p>
                    </div>
                </div>     
                {!! $f->thumbnail !!}
            </a>
        </div>
    </div>
@endforeach
```

I’m having trouble attempting to pass the ACF data to the loop. I’m trying to pass the ACF location field. I’m not having any luck with anything I try and can’t find any examples that others have used to make this work.

---

## Post 55 by @joshb — 2020-06-17T22:34:50Z

I apologize in advance for the bump here but I’m still curious if anyone has any suggestions on my last post and getting fields from a post thru a relationship to appear in the loop on the home page.

Much appreciated!

---

## Post 56 by @alwaysblank — 2020-06-18T03:23:39Z

What’s preventing you from doing this?

```
<?php

namespace App\Controllers;

use Sober\Controller\Controller;

class FrontPage extends Controller
{

    public function featured() {
    global $post;
    $data = [];
    $featured = get_field('featured_portfolios');
        foreach ($featured as $f) {
            $post_data = [
                'thumbnail' => get_the_post_thumbnail($f, 'hero', array('class' => 'lozad')),
                'permalink' => get_the_permalink($f),
                'title' => get_the_title($f),
            ];

            $field = get_field('portfolio', $f);
            $portfolio_data = [
                'slider' => $field['slider'] ?? null,
                'name' => $field['name'] ?? null,
                'location' => $field['location'] ?? null,
                'description' => $field['description'] ?? null,
                'awards' => $field['awards'] ?? null,
                'photos' => $field['photos'] ?? null,
            ];
            array_push($data, (object) array_merge($post_data, $portfolio_data));
        }
        return $data;
    }
}
```

I’m sure I understand your use case. Maybe if you showed some of the things you’ve tried it would help us understand what the problem is?

---

## Post 57 by @joshb — 2020-06-18T04:07:40Z

Honestly, lack of knowledge… where can I study up on this? Thanks for the help, I understand more now. I’m sure others will come around and find this information useful as well.

---

## Post 58 by @alwaysblank — 2020-06-18T04:20:15Z

The only interesting things I did there were pass the post object id to [`get_field()`](https://www.advancedcustomfields.com/resources/get_field/) and use [`array_merge()`](https://www.php.net/manual/en/function.array-merge.php) to combine the two arrays. I don’t know where exactly I’d go to study up on them except the ACF and PHP docs? I would recommend at least reading through all of PHP’s many, _many_ array functions: [https://www.php.net/manual/en/ref.array.php](https://www.php.net/manual/en/ref.array.php). Just about everything in PHP is basically an array (which is not great, but…that’s life) so knowing how to manipulate them with language-level functions is very helpful. My personal favs are `array_map`, `array_reduce`, `array_filter`, `array_merge`, and `array_column`.

`get_field()` is generally my only point of contact w/ ACF’s data structure: I know it has a bunch of other functions but to me they just confuse things. `get_field()` gives you a value or an array, and they you can process it however you want. I do see a lot of people apparently unaware that you can pass an ID as the second parameter to tell it to get the field from a specific post object. I usually try and make it a habit to _always_ call `get_field()` with that second parameter, so I can easily know where it’s getting the value from when I look at my code, without having to do a bunch of thinking about the current global context.

---

## Post 59 by @joshb — 2020-06-18T04:27:06Z

That’s amazing. Thanks for sharing your favs and that info! It is super helpful.

---

## Post 60 by @bonlando — 2020-11-28T02:42:53Z

Hey man, I know this is a super old thread, but it’s worth a shot. I"m using this code, it works great. But i’d like to output the number each item in the loop is associated with. Normally I’d use $count = 0 and then $count++; and then echo $count in the loop but I can’t figure out where to place this for it to work.

Cheers!

---

## Post 61 by @alwaysblank — 2020-11-28T06:54:40Z

Put the value of `$count` in the array you build in each iteration.
