I use a github page for my personal website and would like to include a little piece at the bottom that says when the website was last updated (i.e., when the most recent commit was). I have seen questions asking about the API, but I'd also like to know how to integrate this with the GitHub page so it automatically updates this also. The website is on a private repository.
CodePudding user response:
With a little bit of AJAX this can be achieved utilizing the GitHub API.
const desiredRepo = "yoursite.github.io";
const dateTagClass = ".date"; // The HTML element you want to update
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
let repos = JSON.parse(this.responseText);
repos.forEach((repo)=>{
if (repo.name == desiredRepo)
{
var lastUpdated = new Date(repo.updated_at);
var day = lastUpdated.getUTCDate();
var month = lastUpdated.getUTCMonth();
var year = lastUpdated.getUTCFullYear();
$(dateTagClass).text(`Last updated: ${year}-${month}-${day}`);
}
});
}
};
xhttp.open("GET", "https://api.github.com/users/YOUR_USERNAME/repos", true);
xhttp.send();
Make sure to change desiredRepo
to your GitHub pages URL, dateTagClass
to the appropriate class for the element you want to update, and to update the xhttp.open()
call to include your username where it says YOUR_USERNAME
.
CodePudding user response:
It depends what static site generator you are using.
For Jekyll, for instance, you have the plugin gjtorikian/jekyll-last-modified-at
, a liquid tag for Jekyll to indicate the last time a file was modified.
This plugin determines a page's last modified date by checking the last Git commit date of source files.
In the event Git is not available, the file's mtime is used.
With Hugo, you have the lastmod
Git variable, that you can configure (as shown in "Last Modified Date with Hugo" by Andrew Stevens , or in "Last Modified Date in Hugo" from MERT BAKIR)
[frontmatter]
enableGitInfo = true
date = ["date", "publishDate", "lastmod"]
lastmod = ["lastmod", ":git", "date", "publishDate"]
By default,
:git
comes beforelastmod
but the configuration change above allows you to still definelastmod
in your front-matter to overridegit
derived dates if you wish.You can now display lastmod:
<p>Last Modified: {{ .Lastmod.Format "2 January 2006" }}</p>
With 11ty/eleventy
, you would use contentDate
: see issue 330.
The goal is, of course, to not use a dynamic script (with API call) in your page, since it would involve an API call each time you access the page.
The "last modification" should be a static data, generated once when you are building and publishing your page.