"constantize" string to avoid {% when %}

Hi! I have two .yml files with the same structure contained in a folder into _data folder named the same as a variable defined in a front matter of a page where I’d like to use one of them (see image below)
Schermata 2021-08-07 alle 16.06.43
In Ruby language there is a very useful function called constantize that evaluate a string as it would be part of the source code of the page. Does it exists a similar construct in Jekyll or Liquid? (I didn’t find it).
To be more clear this is my use case: starting from the image above I’v this code

            {%- case page.title -%}
            {%- when "branding" -%}
            {%- for service in site.data.branding.services -%}
            {% capture service_side_style %}{% cycle 'left', 'right' %}{% endcapture %}
            {%- include service.html description=service align=service_side_style -%}
            {%- endfor -%}
            {%- when "ecommerce" -%}
            {%- for service in site.data.ecommerce.services -%}
            {% capture service_side_style %}{% cycle 'left', 'right' %}{% endcapture %}
            {%- include service.html description=service align=service_side_style -%}
            {%- endfor -%}
            {%- else -%}
            should not happen....
            {%- endcase -%}

The code in every {% when %} is almost the same and in the {% for %} loop I use the same collection name as the case I’m in since I switch on the page name. Using a code like the one below (but it doesn’t work unfortunately :grinning_face_with_smiling_eyes:) would be the best since it would be short (no when required), dynamic (I can add as many folder with the same structure in the _data directory without update the {% when %})

{% assign my_var=page.name | constantize %}
{% for service in site.data.my_var.services %}

Thank you very much!

not sure I understand exactly what you want, but down below it has page.name - is that something you set as a page variable? not sure name is a normal one. Above you have page.title and I would think that would work below (without the constantize bit). Did you try that? if the page title is branding I think it would work. And on the ecommerce page it would also work.

Never heard of constantize, don’t think it is a think in Jekyll.

1 Like

Data hashes/objects/arrays can be accessed with a variable using the array[index_variable] form. Here’s an example (tested code):

Given _data/foo.yml:

name: foobar

Then the following:

{% assign file='foo' %}
{{ site.data[file].name }}

Will output “foobar”

2 Likes

Thank you! I didn’t knew I could access to .yml file like this!!

Thank you too, I’ll try your solution too! I’m sorry, I forgot to mention that yes, “name” is a page variable and my file is intended to be used as a layout for other pages