Last active
June 15, 2021 19:48
-
-
Save wdzajicek/aa4753f89eb7ac1e339358340a9c7982 to your computer and use it in GitHub Desktop.
Create a sitemap in a Jekyll project with 2 files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Save this file in your Jekyll `_plugins/` dir | |
Jekyll::Hooks.register :pages, :pre_render do |page| | |
# get the page's last modified time | |
modification_time = File.mtime( page.path ) | |
# inject modification_time into page's data. | |
page.data['last-mod-time'] = modification_time | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
layout: null | |
--- | |
{% comment %} | |
THIS FILE REQUIRES A PLUGIN FILE: | |
Save the following code as `_plugins/last-mod-time.rb`: | |
Jekyll::Hooks.register :pages, :pre_render do |page| | |
# get the page's last modified time | |
modification_time = File.mtime( page.path ) | |
# inject modification_time into page's data. | |
page.data['last-mod-time'] = modification_time | |
end | |
{% endcomment %} | |
<?xml version="1.0" encoding="UTF-8"?> | |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"> | |
{%- for page in site.pages -%} | |
{% unless page.url contains '.xml' %} | |
<url> | |
<loc>{{ site.url }}{{ page.url }}</loc> | |
<lastmod>{% if page.last-mod-time %}{{ page.last-mod-time | date: '%Y-%m-%dT%H:%M:%S.%LZ' }}{% else %}{{ 'today' | date: '%Y-%m-%dT%H:%M:%S.%LZ' }}{% endif %}</lastmod> | |
</url> | |
{%- endunless -%} | |
{%- endfor -%} | |
{%- for file in site.static_files -%} | |
{% if file.extname == '.pdf' %} | |
<url> | |
<loc>{{ site.url }}{{ file.path }}</loc> | |
<lastmod>{{ file.modified_time | date: '%Y-%m-%dT%H:%M:%S.%LZ' }}</lastmod> | |
</url> | |
{%- endif -%} | |
{% endfor %} | |
</urlset> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For some reason
last-mod-time.rb
can't get theFile.mtime( page.path )
for some of the pages. Consequently, thesitemap.xml
template checks forpage.last-mod-time
first and uses it if it exists. If{% if page. last-mod-data %}
returns false (it doesn't exist,) then the current date/time are used instead as a backup.