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

标签 javascript underscore.js momentjs swig-template keystonejs

我正在扩展 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
});

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

适用于原始模型的原始 View 代码:

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

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

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

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

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

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



编辑:
它变得更加奇特......下面似乎有效:

{% 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') }} 

关于javascript - 无法格式化 keystone.js 中的嵌套日期字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350601/

相关文章:

javascript - 使用 Appcelerator 将基于 web2py 的 Web 应用程序转换为 native 应用程序,容易吗?可能的?

javascript - 根据函数参数动态调用javascript函数

underscore.js - 如何在 underscore.js 模板中打印数组?

javascript - 无法理解条件 IF 语句代码

javascript - 循环通过背景图像 onClick 工作 - 但仅在 secondClick

javascript - 可以在下划线模板中访问 'root' 模型吗?

javascript - Moment js diff函数在 native react 中不起作用

angular - 在 Angular Typescript 库中使用 MomentJS 时出错

JavaScript 间隔函数来计算日期时间

javascript - D3 : data update "enter" selection is empty