fix(sitemap): use latest post's date as <lastmod>

- posts[0] is used instead of posts.first() because first()
is not available after posts.toArray()
This commit is contained in:
MDLeom 2020-07-01 07:46:16 +01:00
parent 791f845ca3
commit a2a68d3291
No known key found for this signature in database
GPG Key ID: 5D9DB57A25D34EE3
4 changed files with 21 additions and 17 deletions

View File

@ -4,30 +4,29 @@
<url>
<loc>{{ post.permalink }}</loc>
{% if post.updated %}
<lastmod>{{ post.updated }}</lastmod>
<lastmod>{{ post.updated | formatDate }}</lastmod>
{% elif post.date %}
<lastmod>{{ post.date }}</lastmod>
<lastmod>{{ post.date | formatDate }}</lastmod>
{% endif %}
</url>
{% endfor %}
{# home page #}
<url>
<loc>{{ config.url + config.root }}</loc>
<lastmod>{{ sNow }}</lastmod>
</url>
<loc>{{ config.url + config.root }}</loc>
<lastmod>{% if posts[0].updated %}{{ posts[0].updated | formatDate }}{% else %}{{ posts[0].date | formatDate }}{% endif %}</lastmod>
</url>
{# archive page #}
<url>
<loc>{{ config.url + '/' + archive_dir + '/' }}</loc>
<lastmod>{{ sNow }}</lastmod>
<loc>{{ config.url + '/' + config.archive_dir + '/' }}</loc>
<lastmod>{% if posts[0].updated %}{{ posts[0].updated | formatDate }}{% else %}{{ posts[0].date | formatDate }}{% endif %}</lastmod>
</url>
{# tag pages #}
{% for tag in tags %}
<url>
<loc>{{ tag.permalink }}</loc>
<lastmod>{{ sNow }}</lastmod>
</url>
<url>
<loc>{{ tag.permalink }}</loc>
<lastmod>{% if tag.posts.first().updated %}{{ tag.posts.first().updated | formatDate }}{% else %}{{ tag.posts.first().date | formatDate }}{% endif %}</lastmod>
</url>
{% endfor %}
</urlset>

View File

@ -39,9 +39,7 @@ module.exports = function (locals) {
// configuration dictionary
const xmlConfig = {
config: config,
posts: posts,
// add current time to <lastmod> of homepage and tags
sNow: moment().format('YYYY-MM-DD[T00:00:00.000Z]')
posts: posts
}
if (config.sitemap.tags !== false) {

View File

@ -9,7 +9,8 @@
const pathFn = require('path')
const config = hexo.config.sitemap = Object.assign({
path: 'sitemap.xml'
path: 'sitemap.xml',
tags: true
}, hexo.config.sitemap)
if (!pathFn.extname(config.path)) {

View File

@ -2,6 +2,7 @@
const { join } = require('path')
const { readFileSync } = require('fs')
const moment = require('moment')
let sitemapTmpl = ''
module.exports = function (config) {
@ -13,6 +14,11 @@ module.exports = function (config) {
watch: false
})
env.addFilter('formatDate', str => {
if (typeof str === 'string') return str.substring(0, 10)
return moment(str).format('YYYY-MM-DD[T00:00:00.000Z]').substring(0, 10)
})
const sitemapSrc = config.sitemap.template || join(__dirname, '.sitemap.xml')
sitemapTmpl = nunjucks.compile(readFileSync(sitemapSrc, 'utf8'), env)