Thijs
Thijs

Reputation: 717

How to dynamically assign _data variable?

I'm using staticman to enable comments on my blog. It puts the comments in the _data folder. My folder structure then looks like this:

_data/
    comments/
        blog-post-1/
            entry1542891129928.yml
            ...
        blog-post-2/
            entry1542891129928.yml
            ...
        ...

In my _layouts/post.html I want to access comments for a specific blog. This is the code that I expect to work to get to the comments:

{% assign comments = site.data.comments[page.slug] | sort %}

But when I run build, I get the following error:

Liquid Exception: Liquid error (line 39): Cannot sort a null object. in /_layouts/post.html

It seems to be something to do with page.slug because if I replace it with the string 'blog-post-1' it works.

How to get the post slug dynamically in post.html?

Upvotes: 2

Views: 107

Answers (1)

Thijs
Thijs

Reputation: 717

Solved the problem!

The issue is when the folder does not exist. I circumvent this by moving the sort filter:

{% assign comments = site.data.comments[page.slug] %}
{% if comments %}
    {% assign comments = comments | sort %}
    ...do things...
{% endif %}

Now the build doesn't fail.

Upvotes: 4

Related Questions