Passing a field name from CFS wordpress plugin through to twig

When using Timber you can easily pass variables from your PHP controller through to your twig view. There are 2 ways to do this:

1) In functions.php you can pass variables globally to the context. The Timber Starter theme has this in it for reference. Your add_to_content function, should look like:

function add_to_context( $context ) {
    global $cfs;

    $context['header_image'] = $cfs->get('header_image');

Think of $context as a giant variable that passes through your variables into that actual view.

Remember: this makes your variables globally accessible, so you will need to name your CFS id’s uniquely. For example global_phone_number.

2) To better structure your code, you should pass through your variables to the context, via the controller for that page. This helps ensure that you don’t pass around variables that aren’t being used.

In your page.twig file, you will need to add:

$context['header_image'] = $cfs->get('header_image');

Remember: the $context name is what you use in your twig file, and $cfs name is what you called it in Custom Field Suite.


Lastly:

The {% if header_image %} is good, as this will check whether a variable has been set, and then decided whether to show this block. However, in CFS, when an image is uploaded, it gives you the option to select File URL or Attachment ID. This means you will need to handle this result in your twig file.

For example, by choosing File URL, you will need to output the {{header_image}} as:

<img src="{{header_image}}" />

You may also then want to add in the alt attribute based on the images alt text set in WordPress media library.

Leave a Comment