Craft CMS Asked on August 26, 2021
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!
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]
Correct answer by James Smith on August 26, 2021
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 %}
Answered by Roi Agneta on August 26, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP