2

I would like to use hexo such that I have a sidebar that appears on every page (a sidebar in layout.ejs) which has links to all my posts in reverse chronological order.

In my theme I have a sidebar.ejs snippet that looks like this:

<div class="sidebar-links-wrapper">
     <% site.posts.each(function(item){ %>
            <a href="<%- config.root %><%- item.path %>" class="navlink"><%- item.title %></a>
       <% }); %>
</div>

But site.posts does not appear to be in the correct order. It doesn't show by order of the post creation date.

In index.ejs I have a section where the posts show up in the correct order (using page.posts).

<% page.posts.each(function(item){ %>
 -- some other stuff
<% }); %>

However, I can't use page.posts in sidebar.ejs because layout.ejs includes sidebar.ejs and it appears to throw an error that page is not found if I reference the page variable.

Is there a way to correctly order site.posts? Or a way to reference page.posts from layout.ejs? Or a different way to achieve my desired effect?

Thank you for any help.

maxfowler
  • 1,168
  • 13
  • 23
  • my theme was based off of this tutorial: http://www.codeblocq.com/2016/03/Create-an-Hexo-Theme-Part-1-Index/ – maxfowler Jun 25 '16 at 19:08

3 Answers3

3
<div class="sidebar-links-wrapper">
    <%
        // Fast array clone
        var posts = site.posts.slice(0);
        posts.sort(function(a, b){
          return a.date < b.date
        });
    %>
    <% posts.forEach( function(item, i) { %>
        <a href="<%- config.root %><%- item.path %>" class="navlink"><%- item.title %></a>
    <% } %>
</div>
2

in Hexo 3:

<% site.posts.sort('date', -1).each(function(item){ %>
     <%- item.title %></a>
<% }); %>
Valentin E
  • 1,363
  • 11
  • 11
1

I was able to sort site.posts in sidebar.ejs using Javascript.

Here is the snippet from my sidebar.ejs below:

 <div class="sidebar-links-wrapper">
         <%
             var posts = [];
             site.posts.forEach(function(item){
                 posts.push(item);
             });
             posts.sort(function(a, b){
                 return a.date < b.date
             });
       %>
         <% for (i = 0; i < posts.length; i++) {  var item=posts[i]; %>
                <a href="<%- config.root %><%- item.path %>" class="navlink"><%- item.title %></a>
           <% }; %>
    </div>
rockerest
  • 10,412
  • 3
  • 37
  • 67
maxfowler
  • 1,168
  • 13
  • 23
  • Tried this today (January 15th, 2017) and it worked. The other answer did not. I've updated with the specific syntax I used. I'm confident the problem is that `site.posts` is not a *real* array, so `posts.sort` in the other answer was never called. – rockerest Jan 16 '17 at 05:17