Jekyll Liquid Code Samples

» Posted on August 9 2014 in Code

While learning to use Jekyll I am coming up with little Liquid code snippets that do cool things. Many times what i want to do isn’t really the same as what I can find samples of in the Jekyll documentation or on StackOverflow.

Below are a few things I have used - maybe they will be of help to someone!

Get all articles, listed by Tag from a specific Category:

{% assign sorted_tags = site.tags | sort %}
{% for tag in sorted_tags %}
{% assign zz = tag[1] | where: "category", "Photoshop" | sort %}
{% if zz != empty %}
<h2 id="{{tag[0] | uri_escape }}">{{tag[0]}}</H2>
<ul class="posts">
{% for p in zz %}
  <li itemscope>
  <a href="{{ p.url }}">{{ p.title }}</a>
  <span class="entry-date"> 
  &raquo; <time datetime="{{ p.date | date_to_xmlschema }}" itemprop="datePublished">
  {{ p.date | date: "%B %d, %Y" }}
  </time>
  </span>
  </li>
  {% endfor %}
</ul>
{% endif %}
{% endfor %}

Get related posts - this will list out other posts that have the same Tag as the current post. Use this to build a related posts section under a post.

{% assign vidtag = page.tags  %}
{% assign cat = page.category %}
<div class="row">
	<div class="col-md-12">
	<p>Below are all of our other videos from the '{{vidtag}}' 
	Sub Category. Still want more? Check out all of our  
	<a href="/{{cat}}/">{{cat}} videos here.</a> 
	</p>
	<hr />
	</div>
</div>
<div class="row">
	{% for post in site.posts reversed  %}
	{% if post.tags == vidtag %}
	<div class="col-md-6">
	<p>
	<a href="{{ post.url }}" title="{{ post.title }}">{{ post.title | truncate:52 }}</a>
	</p>
	</div> 
	{% endif %}
	{% endfor %}	
</div>

To get the fancy box that the code on this page is displayed in you need some css - my stock css didn’t have it so I wasn’t getting the box styles. It looks like Markdown/Jekyll is outputting code blocks into a <Pre> and <pre><code>tags. Then as long as it is not Liquid code, just indent 4 spaces and it should render properly. This is the CSS I have for <pre> and <code>

code {
   color: #52595d;
  -moz-background-clip: padding;
  -webkit-background-clip: padding-box;
  background-clip: padding-box;
  background-color: #F3F3F3;
  padding: 0px 3px;
  display: inline-block;
  margin: 0px;
}
pre {
  border: 1px solid #cacaca;
  line-height: 1.2em;
  padding: 10px;
  overflow:auto;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  -moz-background-clip: padding;
  -webkit-background-clip: padding-box;
  background-clip: padding-box;
  background-color: #F3F3F3;
  color: #393939;
  margin: 10px;
}
code,
kbd,
pre,
samp {
  font-family: monospace, monospace;
  font-size: 1em;
}

If you are trying to show a Liquid code block it is a little bit of a pain - you can wrap it in {raw} and {endraw} (% symbols left out for ease but they need to be in there).

Check out this post for great info on showing Liquid in a code block: http://truongtx.me/2013/01/09/display-liquid-code-in-jekyll/.