I am using Craft 3 with the Commerce 2 plugin.

I am trying to dynamically call a variable in a twig template where this variable has to be a "placeholder" for a handle of a field inside a block inside a matrix field.

Here is an example snippet which visualises my problem:

{# 'product' variable is passed to this template #}

{% set fields = product.productFields %}
{% set categoryOptions = [] %}
{% for cats in fields.type('categories') %}
    {% for category in categories.fieldLayout.fields %}
        {% set categoryOptions = categoryOptions|merge([category.name]) %}
    {% endfor %}
{% endfor%}

{% set productId = product.id %}
{% for catOption in categoryOptions %}
    {# Here is where I try to call catOption as a 'placeholder' #}
    {% set productId = productId~ '-'~ categories.(#{catOption}).label %}
{# I have also tried using:
#{catOption} etc but nothing seems to work #}
{% endfor %}

Usually I could call the 'categories' one by one but I want everything to be dynamically set.

I know that in some languages you can call a function/property like that or assign a variable with such value.

Any suggestion for a solution or a workaround would be useful. Thank you in advance!


Unless I'm misunderstanding, the title of your question is a bit misleading as you're not trying to call a Craft function in Twig, you're trying to output a dynamically named variable (a variable variable).

You can generally do that using the array syntax: e.g. categories[catOption].

  • 1
    You are the real MVP! And yes, I was wondering how to format my title. A variable variable was indeed the closest I could call it. Thank you! – ves Sep 25 '19 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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