无法格式化keystone.js中的嵌套日期字段

Cannot format nested date field in keystone.js

本文关键字:嵌套 日期 字段 js 格式化 keystone      更新时间:2023-09-26

我正在扩展keystone.js以支持模型中的多种语言。

原始型号如下:

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

我的扩展模型如下:

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
});

我在视图模板中使用嵌套的publishedDate属性时遇到问题。

使用原始模型的原始视图代码:

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

为我的新模型调整了视图代码(这就是我遇到问题的地方):

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

使用post[lang].xxxxxx,我可以参考我帖子中的所有其他项目(例如post[lang].title.

我是否遗漏了导致这些嵌套下划线函数失败的原因,并出现以下错误?

non_object_property_load为请求引发错误"/en/blog
TypeError:无法读取未定义的属性"publishedDate"



编辑:
它变得更加奇特。。。以下似乎有效:

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

如果有人能解释为什么这是有效的(或更好的方法来实现这一点),我将不胜感激

@JRulle,我假设错误在以下行:

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

问题是下划线方法属于List对象。例如,要访问post.en.publishedDate的下划线方法,可以使用以下语法:post._.en.publishedDate.format('MMMM DD, YYYY')

您应该将上面的行更改为:

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