1

I am trying to use a lookup table technique I saw in a recent Craft Link List post, but getting errors.

The general objective is to auto-generate button text from an array of possibilities using a Matrix block type as a key. Here is my code:

    {% set buttonText = {
    "video" : "Watch the Video",
    "podcast" : "Listen Now",
    "externalLink" : "Visit Site",
    }   
%}


{# resource is a Matrix fieldtye #}
{% set resources = entry.resource.all() %}
{% for block in resources %}
    {% set text = buttonText[(block.type)] %}
    <div>
        <h2>{{ block.heading }}</h2>
        <p>{{ block.description }}</p>
        <a href="#" class="button">{{ text }}</a>
    </div>  
{% endfor %}

The problem is trying to figure out how to use variable as a key in this statement: set text = buttonText[(block.type)], where buttonText is the array and block.type is the key. The value of block.type is correct and matches the key in the array, so I am guessing the syntax is wrong, but can't get it figured out.

Thanks for any suggestions!

1

2 Answers 2

3

Your example isn't working because block.type is actually a shorthand for block.type.handle. Use the latter instead and it should work. You can tell this is the case by dumping out block.type - it's not a simple string, it's a great big object.

buttonText[block.type.handle]

1
  • thanks again, James!
    – Roi Agneta
    Commented Jul 23, 2020 at 22:29
1

Thanks @james smith, that did the trick!

Revised code:


        {% set buttonText = {
    "video" : "Watch the Video",
    "podcast" : "Listen Now",
    "externalLink" : "Visit Site",
    }   
%}


{# resource is a Matrix fieldtye #}
{% set resources = entry.resource.all() %}
{% for block in resources %}
    {% set text = buttonText[(block.type.handle)] %}
    <div>
        <h2>{{ block.heading }}</h2>
        <p>{{ block.description }}</p>
        <a href="#" class="button">{{ text }}</a>
    </div>  
{% endfor %}

1
  • good stuff... if you could accept my answer instead of adding your own, that would be appreciated! Commented Jul 23, 2020 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.