2

I'm using a single template to display entries from several structures. Each structure has a cooresponding global field that is an entries field. I use this to display related entries as a sidebar. These fields are named sidebars.[structure handle]Sidebar, so fore example my blog sidebar global field would be sidebar.blogSidebar.

Coding the sidebar manually works fine, like this:

{% for block in sidebars.blogSidebar %}
    ...
{% endfor %}

But I'm trying to dynamically set the related entries field, and it isn't working:

{% set sidebar = "sidebars." ~ entry.section.handle ~"Sidebar" %}
{% for block in sidebar %}
    ...
{% endfor %}

This code doesn't output anything. If i just output {{ sidebar }}, it shows what I expect, ex: sidebars.blogSidebar.

And if I manually add it to the for loop {% for block in sidebars.blogSidebar %}, it works as expected.

Is there a different way to concatenate the name to make this work?

1 Answer 1

1

I don't think your approach makes sense but you can use twigs Attribute function

{% for block in attribute(sidebar, entry.section.handle ~"Sidebar") %}
3
  • Thanks. This worked: {% set sidebar = listingSettings[entry.section.handle ~"Sidebar"] %}
    – artmem
    Commented Mar 5, 2018 at 23:45
  • If you want, we can talk in the chat about your Craft structure. It's not meant to be abused that way and there are many better, cleaner and faster approaches. That are much easier to handle and to extend in the future Commented Mar 5, 2018 at 23:50
  • Thanks. I appreciate that. Always interested in learning new/better ways to do things.
    – artmem
    Commented Mar 6, 2018 at 19:40

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.