String filters in Liquid

Episode #8 - Mar 30, 2016 - 6 minutes

Subscribe to Jekyll Casts

Liquid string filters allow us to modify string variables. In this example we having a heading variable in front matter we’re outputting as an h2.

---
layout: default
title: Home
heading: Fresh, homemade baked goods
---
<section class="hero">
  <div class="small-container">
    <h2>{{ page.heading }}</h2>
    <p class="sub-text">Bakery<strong>Store</strong> serves the freshest baked goods in San Francisco.</p>
  </div>
</section>
...

Starting

Let’s say we’re outputting heading string in multiple places across this page but each time, we want the output to be slightly different. In this first instance, instead of saying “baked goods” we want it to say “baked bread”. This is an excellent use case for liquid filters.

To use a filter we’ll add a “|” after the variable then pass it a filter, replace in this case.

...
<h2>{{ page.heading | replace: "goods", "bread" }}</h2>
...

Replace

We can also chain filters together, so let’s make the heading uppercase as well.

...
<h2>{{ page.heading | replace: "goods", "bread" | upcase }}</h2>
...

Upcase

Below is a list of all the liquid string filters available. Head over to the Jekyll Cheat Sheet to see all filters you can use.

Filter Output
{{ "cupcake" | prepend: "chocolate " }} chocolate cupcake
{{ "lemon" | append: " cake" }} lemon cake
{{ "i like cupcakes" | capitalize }} I like cupcakes
{{ "BakeryStore" | downcase }} bakerystore
{{ "apple pie" | upcase }} APPLE PIE
{{ "muffin&cupcake?" | cgi_escape }} muffin%26cupcake%3F
{{ "<h1>Banana Split</h1>" | escape }} <h1>Banana Split</h1>
{{ "blueberry muffin.html" | slugify }} blueberry-muffin-html
{{ "<h1>Greentea cheesecake</h1>" | strip_html }} Greentea cheesecake
{{ "**Sour dough** bread" | markdownify }}

Sour dough bread

{{ "I really really like cupcakes" | remove_first: 'really' }} I really like cupcakes
{{ "I really really like cupcakes" | remove: 'really' }} I like cupcakes
{{ "I really really like cupcakes" | replace_first: "really", "truly" }} I truly really like cupcakes
{{ "I really really like cupcakes" | replace: "really", "truly" }} I truly truly like cupcakes
{{ "Carrot cake" | size }} 11
{{ "Peanut butter cheesecake" | number_of_words }} 3
{{ "Souffle" | slice: 0 }} S
{{ "Souffle" | slice: 1 }} o
{{ "Souffle" | slice: -2 }} l
{{ "Souffle" | slice: 2,4 }} uffl
{{ "apple,banana,carrot" | split:"," | jsonify }} ["apple","banana","carrot"]
{{ "The freshest bread in San Francisco" | truncate: 15 }} The freshest...
{{ "Who ate all the cupcakes?" | truncatewords: 3 }} Who ate all...

Subscribe to Jekyll Casts