Luke
Luke

Reputation: 5612

Locomotive CMS: Dynamically Target content_types with Liquid Variable

I'm building a custom navigation snippet in Locomotive CMS and I want content_type entries to be listed in the navigation along with pages.

Specifically (and obviously) I only want entries listed if the content_type has a content_type_template set up.

My plan was to set a handle (refereneced here but ultimately missing from the documentation) on the content_type_template page and then run the following logic when iterating through pages:

{% assign myContentType = loopPage.handle %}

{% for item in contents.myContentType %}

    <li>a href="{{ item._slug }}">{{ item.name }}</a></li>

{% endfor %}

But I've run into a problem: It seems I can't use a variable in this way. I assume there's some kind of issue with trying to plug a variable with a string value in place of a content_type slug. I wouldn't have thought it would be a problem, but it doesn't work.

I also tried:

{% for item in contents[myContentType] %}

and just to be sure:

{% for item in contents[myContentType].items %}

No joy.

How can I dynamically target content_types in Locomotive CMS using a Liquid variable?

Upvotes: 0

Views: 131

Answers (1)

Luke
Luke

Reputation: 5612

Apparently you can't use a Liquid Variable to dynamically target content_types in Locomotive CMS. Specifically, this won't work:

{% assign myVariable = some_string_that_is_the_same_as_a_content_type_slug %}

{% for item in contents.myVariable %}

I tried a number of methods and came to the conclusion that either:

  • Liquid syntax simply doesn't accept a varibale in this context, or
  • the Locomotive CMS implementation of Liquid doesn't facilitate it.

(I'd welcome confirmation or clarification on this point as I'm drawing on anecdotal evidence, not documentation.)

In the end, however, I was able to access content_type entries dynamically using the Locomotive CMS RESTful API. This is largely undocumented and a completely separate topic - one which warranted its own Q & A, which I have created here.

Below is the code I used to dynmically access content_type entries. (For brevity I have included only this snippet which sits inside a number of Liquid loops to build the menu items and sub items.)

{% assign myContentType = loopPage.handle %}

{% action "get content_type entries" %}
    var contentData = false;
    contentData = callAPI('GET', 'https://station.locomotive.works/locomotive/api/v3/content_types/{{ myContentType }}/entries.json', {
        data: {
        },
        headers: {
            'X-Locomotive-Account-Email': '[my-account-email-adddress]',
            'X-Locomotive-Site-Handle': '[my-site-handle]',
            'X-Locomotive-Account-Token': '[my-account-token]'
        }
    });
    setProp('contentData', contentData);
{% endaction %}

{% for item in contentData.data %}

    <li><a href="{{ item._slug}}">{{ item.name }}</a></li>

{% endfor %}

Upvotes: 0

Related Questions