Search code examples
if-statementgithubconditional-statementsgithub-pagesblogs

Github Pages: adding an if condition in index.html


I have a blog created on Github Pages using Jekyll Now

The default Index.html looks like this

---
layout: default
---

<div class="posts">
  {% for post in site.posts %}
        <article class="post">

          <h2><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a></h2>

          <div class="entry">
            {{ post.excerpt }}
          </div>

          <a href="{{ site.baseurl }}{{ post.url }}" class="read-more">Read More</a>
        </article>
  {% endfor %}
</div>

This creates a landing page where the titles of all the posts you have made in the _posts directory are displayed with a link.

Looking at the {% for ... %} & {% endfor %} & the final static HTML, it seems as if when building the page, the for tag is actually iterated & the final HTML contains a list of actual titles.

I want to change this so that not all posts are listed. I do not want to list any post whose title contains the string "BEINGWRITTEN"

I tried stuff like

{% for post in site.posts %}
    {% if (post.title.indexOf('BEINGWRITTEN') == -1) %}
        <article class="post">
...
        </article>
    {% endif %}
{% endfor %}

Also tried with includes instead of indexOf, that also doesn't work. Both cases, I don't see any posts linked at all on the landing page.

How do I do this?


Solution

  • I did this by adding a category in the front matter of the page I don't want included.

    i.e. category: noshow

    Then changed the index.html to

       {% for post in site.posts %}
    
          {% unless post.category == "noshow" %}
    
              .....
    
          {%endunless}
    
       {%endfor}