Search code examples
javascriptunderscore.jsmomentjsswig-templatekeystonejs

Cannot format nested date field in keystone.js


I am extending keystone.js to support multiple languages in the models.

The original model looks like this:

Post.add({
    title: { type: String, required: true },
    publishedDate: { type: Types.Date, index: true },
    //... more irrelevant fields
});

My extended model looks like this:

Post.add({
    title: { type: String, required: true },
    en: {
        title: { type: String },
        publishedDate: { type: Types.Date, index: true },
        //... more irrelevant fields
    },
    es: {
        title: { type: String },
        publishedDate: { type: Types.Date, index: true },
        //... more irrelevant fields
    },
    //... more languages following the same pattern
});

I am having an issue using the nested publishedDate properties within the view templates.

Original view code that works with the original model:

{% if post.publishedDate %}
    <br>on {{ post._.publishedDate.format('MMMM DD, YYYY') }}
{% endif %}

Adjusted view code for my new model (this is where I am having the issue):

{% if post[lang].publishedDate %}
    <br>on {{ post[lang]._.publishedDate.format('MMMM DD, YYYY') }}
{% endif %}

Using post[lang].xxxxxx I can refer to all of the other items in my post (for example post[lang].title.

Am I missing something that is causing these nested underscore functions to fail with the following error?

non_object_property_load Error thrown for request" /en/blog
TypeError: Cannot read property 'publishedDate' of undefined



EDIT:
It gets more peculiar... below seems to work:

{% if post[lang].publishedDate %}
    <br>on {{ post._[lang].publishedDate.format('MMMM DD, YYYY') }}
{% endif %}

If anyone can offer up an explanation of why this works (or a better way to accomplish this), I would really appreciate it.


Solution

  • @JRulle, I assume the error is on the following line:

    <br>on {{ post[lang]._.publishedDate.format('MMMM DD, YYYY') }}
    

    The issue is that the underscore methods belong to the List object. For example, to access the underscore methods for post.en.publishedDate you would use the following syntax: post._.en.publishedDate.format('MMMM DD, YYYY')

    You should change the above line to:

    <br>on {{ post._[lang].publishedDate.format('MMMM DD, YYYY') }}